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

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.


Basically, auto_ptr transfers ownership to the the pointer to which it gets assigned.
When you pass auto_ptr to a function the ownership of the pointer gets transferred to the receiving pointer in the function argument. The scope of this pointer is till the body of the function only and hence the pointer gets deleted when the function exits.

Read about it in Using auto_ptr Effectively. Herb Sutter explains it nicely & authoritatively.

Tags:

C++

Auto Ptr