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?
}
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.
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.
unique_ptr::getReturns a pointer to the managed object or nullptr if no object is owned.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With