Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 632
lithuak Avatar asked Dec 29 '10 12:12

lithuak


People also ask

What is the significance of auto_ptr?

auto_ptr is a smart pointer that manages an object obtained via new expression and deletes that object when auto_ptr itself is destroyed.

Why was auto_ptr removed?

Since the assignment-semantics was most-disliked feature, they wanted that feature to go away, but since there is code written that uses that semantics, (which standards-committee can not change), they had to let go of auto_ptr, instead of modifying it.

When was auto_ptr deprecated?

The C++11 standard made auto_ptr deprecated, replacing it with the unique_ptr class template. auto_ptr was fully removed in C++17. For shared ownership, the shared_ptr template class can be used. shared_ptr was defined in C++11 and is also available in the Boost library for use with previous C++ versions.

Why would you choose shared_ptr instead of unique_ptr?

In short: Use unique_ptr when you want a single pointer to an object that will be reclaimed when that single pointer is destroyed. Use shared_ptr when you want multiple pointers to the same resource.


1 Answers

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.
like image 167
icecrime Avatar answered Oct 02 '22 00:10

icecrime