Lost1
Lost1

Reputation: 1062

c++ auto_ptr destroyed when passed into a function

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:

  1. Is the pointer copied when passed into UsePointer function? Hence the owernship is transferred?
  2. 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?

Upvotes: 2

Views: 193

Answers (1)

Is the pointer copied when passed into UsePointer function? Hence the owernship is transferred?

Yes. Unless the function parameter is reference qualified, arguments pass by value. For auto_ptr that involves copying, and thus passing ownership.

What do I need to if want spObject not be destroyed? Do I need to pass this pointer by reference?

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.

Also this book is a bit outdated - does the same hold for unique_ptr in c++ 11?

Yes. With the difference that unique_ptr is not copyable, and so cannot pass its ownership away implicitly. To pass a unique_ptr, it must be moved explicitly. The appearance of std:move in the code that passes the pointer into the function gives an explicit visual cue that ownership changes.

Upvotes: 4

Related Questions