What would be a simple C++ program where a std::vector<std::auto_ptr<T>> compiles but fails to execute correctly, whereas the same program with std::vector<std::unique_ptr<T>> compiles and works correctly, for some data type T?
I know that std::auto_ptr has been deprecated or removed; I just want an example involving containers to motivate why it was deprecated or removed.
I'm using g++-10 -std=c++20 on MacOS Big Sur version 11.2.1.
std::auto_ptrsimply cannot be used in standard containers at all. It does not maintain proper semantics under that situation. Which is one of the reasons why move semantics andstd::unique_ptrwere invented in C++11 in the first place.std::auto_ptrwas deprecated in C++11, and removed completely in C++17. So don't use it at all in modern coding.The official reason why
std::auto_ptrwas deprecated is detailed here:http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1856.html#20.4.5%20-%20Class%20template%20auto_ptr
The example given uses
std::sort()on astd::vector<std::auto_ptr<int>>:The conclusion at the end comes down to this: