其他分享
首页 > 其他分享> > c – 返回时是否保证移动对象?

c – 返回时是否保证移动对象?

作者:互联网

我知道当按值将对象传递给函数时,如果存在构造函数,则始终调用移动构造函数,假设没有复制省略.如何按值返回对象?

例如,假设我们有一个具有移动构造函数的类Foo,并且我们有一个返回Foo对象的函数.

Foo g() {
    Foo f;

    // do something with f

    return f;
}

如果我们假设没有RVO,那么移动构造函数是否可以保证被调用?

更新:我想我没有明确表达我的意图.我只是想知道我可以在最坏的情况下移动对象而不是复制.无论是RVO还是NRVO,我很高兴.我还应该说移动构造函数和移动赋值不会被删除并且正确实现.

解决方法:

是.见[class.copy] p32

When the criteria for elision of a copy operation are met or would be met save for the fact that the source object is a function parameter, and the object to be copied is designated by an lvalue, overload resolution to select the constructor for the copy is first performed as if the object were designated by an rvalue. If overload resolution fails, or if the type of the first parameter of the selected constructor is not an rvalue reference to
the object’s type (possibly cv-qualified), overload resolution is performed again, considering the object as an lvalue. [ Note: This two-stage overload resolution must be performed regardless of whether copy elision will occur. It determines the constructor to be called if elision is not performed, and the selected constructor must be accessible even if the call is elided. — end note ]

标签:c,c11,return-value,move-semantics
来源: https://codeday.me/bug/20190927/1822855.html