问题描述
考虑以下代码:
#include <iostream>
using namespace std;
struct I {
I(I&& rv) { cout << "I::mvcotr" << endl; }
};
struct C {
I i;
I&& foo() { return move(i) };
}
};
int main() {
C c;
I i = c.foo();
}
C包含I.而C :: foo()上面使用的成员函数之间的区别是什么?
C contains I. And C::foo() allows you to move I out of C. What is the difference between the member function used above:
I&& foo() { return move(i) }; // return rvalue ref
和以下替换成员函数:
I foo() { return move(i) }; // return by value
对我来说,他们似乎做同样的事情: I i = c.foo();
导致调用 I :: I(I&&);
。
To me, they seem to do the same thing: I i = c.foo();
leads to a call to I::I(I&&);
.
这个例子中没有包含什么后果?
What consequences will there be that is not covered in this example?
推荐答案
除了考虑你写的程序是否有意义(从一个数据成员移动是尴尬 - 但确定,也许有一些用例),在这种情况下,该函数的两个版本最终做同样的事情。
Considerations aside on whether the program you wrote actually makes sense (moving from a data member is awkward - but OK, perhaps there are some use cases), in this case the two versions of that function end up doing the same thing.
然而,作为一般做法,您应该更喜欢通过值返回,因为在许多情况下,它允许编译器执行 copy elision
As general practice, however, you should prefer returning by value, because in many cases it allows the compiler to perform copy elision and elide the calls to the move constructor of the returned type, as permitted by paragraph 12.8/31 of the C++11 Standard.
复制elision允许编译器创建函数的返回值
Copy elision allows the compiler to create the return value of the function directly in the object which should be initialized from the function's return value.
因此,作为一般指导,优先按值返回。
Therefore, as a general guideline, prefer returning by value.
这篇关于“返回值”和“返回值”之间的差异& “按值返回”当你使用std :: move返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!