开发者

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

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?
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜