简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM