在没有复制省略的情况下, copy/move 构造函数是否保证在析构函数之前被调用?
In the absence of copy elision, is the copy/move constructor guaranteed to be called before the destructor?
和标题差不多。考虑这个例子:
MyClass func()
{
MyClass myInstance;
return myInstance;
}
int main()
{
auto myInstance = func();
}
在没有复制省略的情况下,MyClass
的复制或移动构造函数是否保证在析构函数之前被调用,就像对 func()
returns myInstance
的调用一样?我想像 std::shared_ptr
这样的 class 会在按值返回时使用这样的 属性。
此外,依赖这种行为是否存在任何陷阱?
是的。
来自 [stmt.return]/3:
The copy-initialization of the returned entity is sequenced before the destruction of temporaries at the end
of the full-expression established by the operand of the return statement, which, in turn, is sequenced before
the destruction of local variables (6.6) of the block enclosing the return statement.
和标题差不多。考虑这个例子:
MyClass func()
{
MyClass myInstance;
return myInstance;
}
int main()
{
auto myInstance = func();
}
在没有复制省略的情况下,MyClass
的复制或移动构造函数是否保证在析构函数之前被调用,就像对 func()
returns myInstance
的调用一样?我想像 std::shared_ptr
这样的 class 会在按值返回时使用这样的 属性。
此外,依赖这种行为是否存在任何陷阱?
是的。
来自 [stmt.return]/3:
The copy-initialization of the returned entity is sequenced before the destruction of temporaries at the end of the full-expression established by the operand of the return statement, which, in turn, is sequenced before the destruction of local variables (6.6) of the block enclosing the return statement.