删除从函数返回的唯一指针?
Dropping a unique ptr returned from a function?
如果我有一个函数 source
returns 一个 unique_ptr
,并且我有一个函数 sink
按以下方式调用 source
,它有效[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
是否有效?对象 理论上 应该在什么时候销毁?在那条线之后?在函数的最后?
是的,您的代码有效。 source
返回的未命名临时 unique_ptr
将在创建它的完整表达式的末尾被销毁,在本例中是 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。
调用函数的结果 returns 一个对象(而不是一个(n 左值)引用)是一个临时对象,因此它一直存在直到完整表达式结束,这是整个条件本例中的 if 语句。因此代码是有效的。
如果我有一个函数 source
returns 一个 unique_ptr
,并且我有一个函数 sink
按以下方式调用 source
,它有效[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
是否有效?对象 理论上 应该在什么时候销毁?在那条线之后?在函数的最后?
是的,您的代码有效。 source
返回的未命名临时 unique_ptr
将在创建它的完整表达式的末尾被销毁,在本例中是 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。
调用函数的结果 returns 一个对象(而不是一个(n 左值)引用)是一个临时对象,因此它一直存在直到完整表达式结束,这是整个条件本例中的 if 语句。因此代码是有效的。