George wrote:
Auto_ptr is convenient because of it saves our work and provides a
framework to auto-management life cycle to reduce potential resource
leak.
That, and documenting and asserting intention (i.e. ownership) and
making code exception-safe in a painless way.
But why do we sometimes need to call release method on auto_ptr to
go back to the style of manual management? Remember, when we call
release, we need to delete the object instance manually later.
You do that when you want to.
Example 1:
std::auto_ptr<foo> p = some_function();
boost::shared_ptr<foo const> spc(p);
This will transfer ownership from the auto_ptr to the shared_ptr and
for that the shared_ptr will call release().
Example 2:
struct my_container {
void attach( std::auto_ptr<foo> p);
std::auto_ptr<foo> detach(size_t index);
private:
std::vector<foo*> m_elements;
}
In order to move elements into m_elements, the container will have to
invoke release() on the auto_ptr.
As an exercise to the reader, what is wrong with this implementation?
void
my_container::attach( std::auto_ptr<foo> p) {
m_elements.push_back(p.release());
}