函数返回的unique_ptr的作用域是什么

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

本文关键字:作用域 是什么 ptr unique 返回 函数      更新时间:2023-10-16

这能正常工作吗?(参见示例)

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?
}
函数返回的unique_ptr没有作用域,因为作用域只适用于名称。

在您的示例中,临时unique_ptr的生存期以分号结束。(所以,是的,它会正常工作。)通常,当词汇上包含右值的完整表达式被完全求值时,临时对象就会被破坏,该右值的求值创建了该临时对象。

在计算"full expression"后,临时值将被销毁,"full表达式"(大致上)是最大的封闭表达式,在本例中是整个语句。所以它是安全的;doSomething返回后,unique_ptr被销毁。

应该没问题。考虑

int Func()
{
  int ret = 5;
  return ret;
}
void doSomething(int a) { ... }

doSomething(Func());

即使您在堆栈上返回ret,也可以,因为它在调用范围内。