c++stlcopy-constructorunique-ptrauto-ptr

Why unique_ptr works but auto_ptr doesn’t with STL


I have referred to lot of StackOverflow links on these questions where the reason for auto_ptr not working well with STL is std::auto_ptr<> does not fulfill the requirements of being copy-constructible and assignable (since auto_ptr has a fake copy constructor which basically transfers the ownership).

But even unique_ptr doesn't have copy ctor and assignment operator (it's disabled), so how is the requirement of being copy-constructible and assignable fulfilled?


Solution

  • You're looking at the whole thing backwards.

    In C++98/03, we got auto_ptr. This type lies to everyone by pretending that it supports copy semantics when in fact copying it does something very much unlike a copy operation. Therefore, any type which relies on a type providing copy semantics, like certain containers, would not take well to getting an auto_ptr. Of course, you will only find out when your code becomes dysfunctional, not at compile time.

    In C++11, we got unique_ptr, a type which explicitly does not provide copy semantics. Instead, it provides move semantics, and provides them correctly. Therefore, any type which relies on a type providing copy semantics will fail to compile when given a unique_ptr.

    However, the reason unique_ptr came into being at all because the concept of moving an object was added to the language in C++11. When new concepts get added to the language, existing tools, like standard library requirements, are often re-evaluated relative to that language feature.

    For example, types that formerly required copy semantics did not necessarily have to keep that requirement. C++98/03 containers that required copy semantics were updated in C++11 to only require (noexcept) move semantics from a type.

    So it's not that unique_ptr fulfills some requirement that auto_ptr did not. It's that the language changed to no longer need that requirement, but auto_ptr was still lying about what it did, so for backwards compatibility sake, we created a new type that respected the new language features and didn't lie to people.