Auto Ptr

The standard C++ library contains a little-known class template called auto_ptr. Its behaviour is extremely simple: it takes a pointer in its constructor, and it deletes the pointed-to object in its destructor. It also overrides the -> and * operators, so that you can use it just as if it was a regular pointer. For example:

    int main() {
        std::auto_ptr<HtmlDoc> doc(new HtmlDoc());
    } // the document is deleted at this point

An important point to note is that auto_ptr implements move semantics:

    std::auto_ptr<HtmlDoc> a(new HtmlDoc());
    std::auto_ptr<HtmlDoc> b;
    b = a;    // a becomes null; b contains a's former content

This means that auto_ptrs can't be used inside the standard containers, as the containers expect objects with copy semantics (but see BoostSharedPtr).

There are three main uses for auto_ptr. The first is to store class members that are dynamically allocated:

    class MyClass {
        std::auto_ptr<Resource> res;
         MyClass(Resource* r): res(r) { }
    }; // res is automatically freed when the MyClass object is destroyed

This is particularly helpful when an exception may be thrown by the class's constructor.

The second use is when returning pointers from functions:

    std::auto_ptr<Widget> make_widget(int which);

Here we guarantee that the Widget we return will be deleted, even if the caller isn't aware that a Widget is being returned. We also indicate clearly that we're transferring ownership of a Widget from make_widget to the caller.

The third use is in exception safety:

    void safe_function() {
        std::auto_ptr<Resource> res;
        int x = function_that_might_throw();
        res.reset(new Resource(x));
    } // no more mucking about with "if (resource) delete resource;"

As you can see, auto_ptr is extremely useful. It's therefore surprising that so few people know about it.

Helpfully, an auto_ptr can be implicitly converted into a BoostSharedPtr.

Part of the reason it isn't better known is simply that it is so obvious and obviously useful that people have been rolling their own for ages before it became standard. I did one in 1990, for instance. -- dm

C++11 has a new ver. called unique_ptr, which disallows non-moving assignment. This means that its non-copying semantics are compile-time enforced. It otherwise is just auto_ptr with a more descriptive name.

EditText of this page (last edited November 25, 2012) or FindPage with title or text search