Automatically switching the auto_ptr function makes it sink. What for?

I read a few notes about common pointers. The first STL attempt with auto_ptr is said to have the following major disadvantages:

  • They cannot be used in STL containers.
  • Copy transfer right auto_ptr
  • Passing auto_ptr to a function effectively makes it sink

I understand the first two, but I'm not sure what the last means.

Can someone explain this.

Thanks.

+4
source share
2 answers

This is due to the fact that after copying auto_ptr into a variable, you lose ownership of the pointer to the new variable.

If you have:

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

and you call foo with auto_ptr , you make a copy of auto_ptr for foo . This effectively transfers ownership of foo , and therefore the pointer will be deleted after foo completes.

This is really amazing behavior that made me permanently stop using auto_ptr . For simple RAII inside a try block (a basic example of using auto_ptr , as described in books), use boost::scoped_ptr .

+9
source

In principle, auto_ptr transfers ownership of the pointer to which it is assigned.
When you pass auto_ptr to a function, ownership of the pointer is passed to the receiving pointer in the function argument. The scope of this pointer until only the body of the function remains, and therefore, the pointer will be deleted when the function exits.

Read about it in Using auto_ptr Effectively . Herb Sutter explains this beautifully and authoritatively.

+5
source

All Articles