Freddie Freddie - 4 months ago 9
C++ Question

Passing an auto_ptr to a function effectively makes it a sink. Why?

I'm reading some notes about shared pointers.
They say the first attempt by STL with the auto_ptr had the following major drawbacks:


  • They can't be used in STL containers

  • Copying the auto_ptr transfers ownership

  • Passing an auto_ptr to a function effectively makes it a sink



I understand the first two, but am unsure what the last one means.

Could someone please explain this.

Thanks.

Answer

This is because once you copy the auto_ptr into a variable, you forfeit the ownership of the pointer to the new variable.

When you have:

void foo(std::auto_ptr<bar> x);

and you call foo with an auto_ptr, you make a copy of the auto_ptr for foo's use. This effectively transfers ownership to foo and thus the pointer gets deleted after foo is finished.

This is a really surprising behavior that made me definitively stop using auto_ptr. For simple RAII inside a try block (the primary use case of auto_ptr, as described in books), use boost::scoped_ptr.