gpt4 book ai didi

c++ - 对象返回时是否保证被 move ?

转载 作者:IT老高 更新时间:2023-10-28 23:18:58 24 4
gpt4 key购买 nike

我知道,当通过值传递一个对象给函数时,如果有一个 move 构造函数,总是会调用它,假设没有复制省略。按值返回对象呢?

例如,假设我们有一个类 Foo,它有一个 move 构造函数,我们有一个返回 Foo 对象的函数。

Foo g() {
Foo f;

// do something with f

return f;
}

如果我们假设没有 RVO,是否保证调用 move 构造函数?

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

最佳答案

是的。参见 [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++ - 对象返回时是否保证被 move ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11088023/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com