Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the scope of a unique_ptr returned from a function?

Tags:

c++

unique-ptr

Would this work properly? (see example)

unique_ptr<A> source()
{
    return unique_ptr<A>(new A);
}


void doSomething(A &a)  
{  
    // ...
}  

void test()  
{  
    doSomething(*source().get());   // unsafe?
    // When does the returned unique_ptr go out of scope?
}
like image 496
tache Avatar asked May 23 '11 13:05

tache


People also ask

What happens when you return a unique_ptr?

If a function returns a std::unique_ptr<> , that means the caller takes ownership of the returned object. class Base { ... }; class Derived : public Base { ... }; // Foo takes ownership of |base|, and the caller takes ownership of the returned // object.

What happens when unique_ptr goes out of scope?

std::unique_ptr is a smart pointer that owns and manages another object through a pointer and disposes of that object when the unique_ptr goes out of scope. The object is disposed of, using the associated deleter when either of the following happens: the managing unique_ptr object is destroyed.

What does unique_ptr get do?

unique_ptr::getReturns a pointer to the managed object or nullptr if no object is owned.

What happens when you move a unique_ptr?

A unique_ptr can only be moved. This means that the ownership of the memory resource is transferred to another unique_ptr and the original unique_ptr no longer owns it. We recommend that you restrict an object to one owner, because multiple ownership adds complexity to the program logic.


3 Answers

A unique_ptr returned from a function does not have scope, because scope only applies to names.

In your example, the lifetime of the temporary unique_ptr ends at the semicolon. (So yes, it would work properly.) In general, a temporary object is destroyed when the full-expression that lexically contains the rvalue whose evaluation created that temporary object is completely evaluated.

like image 79
fredoverflow Avatar answered Oct 07 '22 16:10

fredoverflow


Temporary values get destroyed after evaluating the "full expression", which is (roughly) the largest enclosing expression - or in this case the whole statement. So it's safe; the unique_ptr is destroyed after doSomething returns.

like image 42
Alan Stokes Avatar answered Oct 07 '22 17:10

Alan Stokes


It should be fine. Consider

int Func()
{
  int ret = 5;

  return ret;
}

void doSomething(int a) { ... }


doSomething(Func());

Even though you're returning ret on the stack it is okay because it's within the calling scope.

like image 27
DanDan Avatar answered Oct 07 '22 16:10

DanDan