Search code examples
c++stlauto-ptr

Why does the interface for auto_ptr specify two copy-constructor-like constructors


I was going through the auto_ptr documentation on this link auto_ptr There is something which i could not fully understand why is it done. In the interface section there are two declarations for its copy constructor

1)

auto_ptr(auto_ptr<X>&) throw (); 

2)

template <class Y> 
     auto_ptr(auto_ptr<Y>&) throw(); 

What purpose is this for.


Solution

  • It's there in case you can implicitly convert the pointers:

    struct base {};
    struct derived : base {};
    
    std::auto_ptr<derived> d(new derived);
    std::auto_ptr<base> b(d); // converts 
    

    Also, you didn't ask but you'll notice the copy-constructor is non-const. This is because the auto_ptr will take ownership of the pointer. In the sample above, after b is constructed, d holds on to nothing. This makes auto_ptr unsuitable for use in containers, because it can't be copied around.

    C++0x ditches auto_ptr and makes one called unique_ptr. This pointer has the same goals, but accomplishes them correctly because of move-semantics. That is, while it cannot be copied, it can "move" ownership:

    std::unique_ptr<derived> d(new derived);
    
    std::unique_ptr<base> b(d); // nope, cannot be copied
    std::unique_ptr<base> b(std::move(d)); // but can be moved
    

    This makes unique_ptr suitable for use in containers, because they no longer copy their values, they move them.