How do I use C++ auto_ptr class?

23 Jun 2012

What is auto_ptr class? It is a template that defines a pointer-like object intended to be assigned an address obtained by new. When an auto_ptr object expires, its destructor uses delete to free the memory. It is an example of smart pointer, which is a class that has pointer-like properties and augment the behavior of a simple pointer.

auto_ptr behaves very much like a simple pointer, with which you can store the address of memory allocated by new and can be derefernced. Here is an example:

void demo()
{
    auto_ptr<double> pd(new double);
    *pd = 25.5;  // dereferencing!

    // do not need to free memory yourself, auto_ptr takes care of that automatically
    return;
}

It is convenient and easy to use, however it does has some caveats: 1. auto_ptr cannot be used to point to dynamically allocated array, because it uses delete not delete []. 2. It institutes the concept of ownership, with only one smart pointer allowed to own a particular object. Assignment transfers ownership. So it is advised that to use auto_ptr with STL container classes, it might not behave as you expected.

Further readings: + Using auto_ptr effectively + auto_ptr reference