Question

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?
}
Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top