auto_ptr_ref documentation here says this
This is an instrumental class to allow certain conversions that allow auto_ptr objects to be passed to and returned from functions.
Can somebody explain how auto_ptr_ref helps in achieving this. I just want to understand the auto_ptr class and its internals
It is rather confusing. Basically,
auto_ptr_refexists because theauto_ptrcopy constructor isn’t really a copy constructor in the standard sense of the word.Copy constructors typically have a signature that looks like this:
The
auto_ptrcopy constructor has a signature that looks like this:This is because
auto_ptrneeds to modify the object being copied from in order to set its pointer to 0 to facilitate the ownership semantics ofauto_ptr.Sometimes, temporaries cannot match a copy constructor that doesn’t declare its argument
const. This is whereauto_ptr_refcomes in. The compiler won’t be able to call the non-const version of the copy constructor, but it can call the conversion operator. The conversion operator creates anauto_ptr_refobject that’s just sort of a temporary holder for the pointer. Theauto_ptrconstructor oroperator =is called with theauto_ptr_refargument.If you notice, the conversion operator in
auto_ptrthat automatically converts to anauto_ptr_refdoes areleaseon the sourceauto_ptr, just like the copy constructor does.It’s kind of a weird little dance that happens behind the scenes because
auto_ptrmodifies the thing being copied from.Random related tanget about C++0x and unique_ptr
In C++0x,
auto_ptris deprecated in favor ofunique_ptr.unique_ptrdoesn’t even have a copy constructor and uses the new ‘move constructor’ which is explicit about the fact that it will modify the object being moved from and leave it in a useless (but still valid) state. Temporaries (aka rvalues) are explicitly always allowed to be arguments to a move constructor.The move constructor in C++0x has a number of other big benefits. It enables the standard STL containers to store
unique_ptrs and do the right thing, as opposed to howauto_ptrs cannot be. It also mostly eliminates the need for the ‘swap’ function as the whole purpose of the swap function is usually to be a move constructor or move assignment operator that never throws.Which is the other expectation. The move constructor and move assignment operator (much like a destructor) are never supposed to throw.