Suppose that we have
void UsePointer (auto_ptr <CSomeClass> spObj)
{
spObj->DoSomething();
}
and we have a main function:
int main()
{
auto_ptr <CSomeClass> spObject (new CSomeClass ());
UsePointer (spObject);
// spObject->DoSomthing (); would be invalid.
}
The book says "the object was destroyed when UsePointer() returned, because variable spObj went out of scope, hence destroyed"
My question is:
- Is the pointer copied when passed into UsePointer function? Hence the owernship is transferred?
- What do I need to if want spObject not be destroyed? Do I need to pass this pointer by reference?
Also this book is a bit outdated - does the same hold for unique_ptr in c++ 11?
Yes. Unless the function parameter is reference qualified, arguments pass by value. For
auto_ptrthat involves copying, and thus passing ownership.You could. But better yet, pass a reference to the object itself. A function shouldn't accept smart pointers unless manipulation of the ownership is involved. If it just needs to do something with pointee, accept a
CSomeClass const&and pass*spObject.Yes. With the difference that
unique_ptris not copyable, and so cannot pass its ownership away implicitly. To pass aunique_ptr, it must be moved explicitly. The appearance ofstd:movein the code that passes the pointer into the function gives an explicit visual cue that ownership changes.