如果我有一个返回 unique_ptr
的函数 source
,并且我有一个调用 source
的函数 sink
> 通过以下方式,它可以正常工作 [clang]。
但是行为是未定义的吗?或者一切都是共生的?
class Foo {
...
bool isValid() { return true; }
...
}
std::unique_ptr<Foo> source() {
auto foo = std::make_unique<Foo>(); // let's pretend this is C++14?
/* ... initialize foo */
return foo;
}
void sink() {
if (source()->isValid()) {
/* do something */
}
/* ... */
}
仅在该行使用 unique_ptr
是否有效? 理论上什么时候应该销毁对象?在那条线之后?在函数结束时?
最佳答案
是的,您的代码有效。未命名的临时 unique_ptr
由 source
返回将在创建它的完整表达式的末尾被销毁,在本例中为 if
中的条件声明。
来自 N3337,§12.2/3 [class.temporary]
... Temporary objects are destroyed as the last step in evaluating the full-expression (1.9) that (lexically) contains the point where they were created. ...
来自§6.4/1 [stmt.select],if
的语法声明是
Selection statements choose one of several flows of control.
selection-statement: if ( condition ) statement ... condition: expression ...
请注意 return std::move(foo);
不需要,可以写return foo;
和 unique_ptr
将是 automatically moved .
关于c++ - 删除从函数返回的唯一指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31659123/