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
I would say it can be used, but it is not the best option.
First, it is a matter of year or less and auto_ptr
is officially deprecated. Second, there is a superior alternative: unique_ptr
. Dr. Stroustrup once said about unique_ptr
:
“What auto_ptr should have been” (but that we couldn't write in C++98)
So unless you don't have the choice, auto_ptr
is not a good choice. Mainly, because most C++ compilers these days implement move semantics
and provide unique_ptr
.
I use std::auto_ptr
moderately often, to ensure exception safety. That is, to prevent a memory leak in the event of part of a method throwing an exception.
For example:
Foo &Container::addFoo(
const std::string &name
)
{
// The post conditions of the method require that the new Foo
// has been added to this container, but the addition method
// may throw exceptiona
std::auto_ptr< Foo > foo(new Foo(name));
foo->twiddle();// may throw
this->addFoo(*foo);// record reference. May throw
return *foo.release();
}
Edited:
clarified that this->addFoo(*foo)
records a reference.
Clearly, auto_ptr
looses against unique_ptr
.
Now, in a 'strict C++03 without boost' world, I use auto_ptr
quite often, most notably :
std::auto_ptr
in the return type explicits that the object must be deletedrelease()
only if std::map<>::insert
returns that insertion succeededconst std::auto_ptr
to make it clear that the message will be destroyed no matter what.In simple scenarios when you need to temporarily control a heap-allocated object auto_ptr
can be used without problems. For example if you need to conditionally create an object that will be used only within one function you can't allocate it on stack and auto_ptr
lets you not care of the object lifetime should an exception occur.