Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

auto-ptr

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.

like image 941
Freddie Avatar asked Jul 31 '11 16:07

Freddie


People also ask

Why was auto_ptr removed?

Since the assignment-semantics was most-disliked feature, they wanted that feature to go away, but since there is code written that uses that semantics, (which standards-committee can not change), they had to let go of auto_ptr, instead of modifying it.

Why is auto_ptr deprecated?

Why is auto_ptr deprecated? It takes ownership of the pointer in a way that no two pointers should contain the same object. Assignment transfers ownership and resets the rvalue auto pointer to a null pointer. Thus, they can't be used within STL containers due to the aforementioned inability to be copied.

Why auto_ptr Cannot be used with STL?

The C++ Standard says that an STL element must be "copy-constructible" and "assignable." In other words, an element must be able to be assigned or copied and the two elements are logically independent. std::auto_ptr does not fulfill this requirement.

When was auto_ptr deprecated?

The C++11 standard made auto_ptr deprecated, replacing it with the unique_ptr class template. auto_ptr was fully removed in C++17. For shared ownership, the shared_ptr template class can be used. shared_ptr was defined in C++11 and is also available in the Boost library for use with previous C++ versions.


1 Answers

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.

like image 198
Alexandre C. Avatar answered Sep 27 '22 17:09

Alexandre C.