Search code examples
c++stlsmart-pointersauto-ptr

Is there any reason to use auto_ptr?


After reading Jossutis' explanation on auto_ptr from his STL book I've got a strong impression that whatever task I would try to use it in I'd 100% fail becuase of one of many auto_ptr's pitfalls.

My question is: are there any real life tasks where auto_ptr is really usefull and does fit there well?


Solution

  • Clearly, auto_ptr looses against unique_ptr.

    Now, in a 'strict C++03 without boost' world, I use auto_ptr quite often, most notably :

    • For 'factory member functions' which return a dynamically allocated instance of a given type : I like the fact that using std::auto_ptr in the return type explicits that the object must be deleted
    • In functions which allocate an object before attempting to insert it in a container afterwards : for example in order to release() only if std::map<>::insert returns that insertion succeeded
    • In a thread procedure which pops elements from a message queue, I like storing the pop'ed element in a const std::auto_ptr to make it clear that the message will be destroyed no matter what.