是否保证在返回对象时移动对象? [英] Is an object guaranteed to be moved when it is returned?

查看:130
本文介绍了是否保证在返回对象时移动对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道当一个对象通过值传递给一个函数时,move constructor总是被调用,如果有一个,假设没有复制elision。例如,假设我们有一个类 Foo ,它有一个移动构造函数,我们有一个返回 Foo 对象的函数。

  Foo g(){
Foo f;

//使用f $ b执行某些操作
$ b return f;
}



如果我们假设没有RVO, ?



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

解决方案

参见[class.copy] p32


当满足复制操作的限制条件或满足以下条件时,源对象是函数参数,并且要被复制的对象由左值指定,则首先执行选择用于复制的构造函数的重载分辨率,如同该对象由右值指定。如果重载解析失败,或者如果所选构造函数的第一个参数的类型不是对
对象的类型(可能是cv限定的)的右值引用,则会将对象视为左值来重新执行重载分辨率。 [注意:无论是否发生复印偏差,都必须执行此两阶段重载分辨率。如果不执行elision,则它确定要调用的构造函数,并且即使调用被省略,所选构造函数也必须可访问。 - 结束注释]



I know that when passing an object by value to a function, the move constructor is always called if there is one, assuming no copy elision. What about returning an object by value?

For example, say we have a class Foo which has a move constructor, and we have a function that returns a Foo object.

Foo g() {
    Foo f;

    // do something with f

    return f;
}

If we assume there is no RVO, is the move constructor guaranteed to be called?

Update: I guess I didn't show my intention clearly. I just want to know I can in the worst case have the object moved not copied. Either RVO or NRVO happens, I am happy. And I should also say that move constructor and move assignment are not deleted and are properly implemented.

解决方案

Yes. See [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 ]

这篇关于是否保证在返回对象时移动对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆