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

3

6

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.

Cudbear answered 31/7, 2011 at 16:19 Comment(2)
It sinks your code. Apply "Copying the auto_ptr transfers ownership".Felicitous
Avoid std::auto_ptr, it got replaced by std::unique_ptr and is deprecated in C++11. In C++17 it will be removed from the standard library.Guthrey
M
10

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.

Manganate answered 31/7, 2011 at 16:23 Comment(0)
P
6

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.

Parmenter answered 31/7, 2011 at 16:22 Comment(0)
S
0

A data sink is something that sucks up your data, taking ownership of it.

The terminology originates in the notion of "pipelines", where some particular entity in a chain of entities takes its data from a "source", then pushes its result to a "sink". The next entity in the chain does the same thing, and so forth. At each stage, the entity can no longer do anything with the data that it's passed on.

By analogy (and example), consider taking data from std::cin (a stream acting as a source), doing some calculations then pushing the result to std::cout (a stream acting as a sink). Once you're done, you're done; the results are out in the ether and you can't get them back.

That's what auto_ptr does: it gives away ownership of your data, whether you wanted it to or not.

Sequestration answered 30/5, 2019 at 10:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.