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.
This is because once you copy the
auto_ptrinto a variable, you forfeit the ownership of the pointer to the new variable.When you have:
and you call
foowith anauto_ptr, you make a copy of theauto_ptrforfoo‘s use. This effectively transfers ownership tofooand thus the pointer gets deleted afterfoois finished.This is a really surprising behavior that made me definitively stop using
auto_ptr. For simple RAII inside atryblock (the primary use case ofauto_ptr, as described in books), useboost::scoped_ptr.