函数返回的unique_ptr的作用域是什么
What is the scope of a unique_ptr returned from a function?
这能正常工作吗?(参见示例)
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,也可以,因为它在调用范围内。
相关文章:
- "using namespace std;"在C++的作用是什么?
- 是同一作用域的函数部分中的函数调用
- atomic_thread_fence的作用域是什么
- 局部变量的作用域是块或函数
- 函数和类的作用域有什么区别
- 函数作用域是静态变量还是线程本地变量在C++11中的第一个条目中初始化
- 变量声明中结构的作用域解析是什么意思
- C++中没有大括号的for循环的作用域是什么
- 什么是C++中的作用域指针
- 此字符串的作用域是什么?
- C++11 Lambda闭包通过引用涉及一个堆栈变量,该变量离开作用域是允许的,但得到了未定义的行为
- C++中类内部的类的作用域是什么
- 用户定义文字的作用域是什么
- 文字值的作用域是什么,编译器如何为它分配内存
- 在c++模板中::*(作用域op后面的星号)是什么意思?
- 解析STD库作用域的路径是什么?
- 添加到QList中的c++类的作用域是什么?
- 在c++中,没有变量名的构造函数调用的生存期/作用域是什么?
- 在类定义的类名中,作用域解析操作符的作用是什么?
- 函数返回的unique_ptr的作用域是什么