[英]Pass by rvalue reference and return using std::move()?
Consider: 考虑:
struct Foo {
Foo () { std::cout << "default ctor" << std::endl; }
Foo (const Foo&) { std::cout << "copy ctor" << std::endl; }
Foo& operator= (const Foo&) { std::cout << "copy op" << std::endl; return *this; }
Foo (Foo&&) { std::cout << "move ctor" << std::endl; }
Foo& operator= (Foo&&) { std::cout << "move op" << std::endl; return *this; }
~Foo () { std::cout << "dtor" << std::endl; }
};
Foo process1 (Foo&& foo) {
return foo;
}
Foo process2 (Foo&& foo) {
return std::move (foo);
}
and usage: 和用法:
Foo foo {};
foo = process1 (std::move (foo));
gives result: 给出结果:
default ctor
copy ctor
move op
dtor
dtor
and usage: 和用法:
Foo foo {};
foo = process2 (std::move (foo));
gives result: 给出结果:
default ctor
move ctor
move op
dtor
dtor
Which one is preferred one (process1 or process2)? 首选哪一个(process1或process2)?
Does it mean that in the first example (process1) if I pass object by rvalue reference to the function, which returns an Object, the copy will be made if I do not use std::move()
? 这是否意味着在第一个示例(process1)中,如果我通过右值引用将对象传递给该函数,该函数返回一个Object,如果我不使用
std::move()
,将进行复制?
Compiler: GCC 5.2.1 编译器:GCC 5.2.1
In the first version 在第一个版本中
Foo process1 (Foo&& foo) {
return foo;
}
you pass it as an rvalue reference, but by the "if it has a name" heuristic , it is treated as an lvalue within the function, hence the copy ctor. 您将其作为右值引用传递,但是通过“如果它具有名称”试探法 ,它将在函数中被视为左值,因此被视为复制ctor。
The second version "remakes" this an rvalue using std::move
(which is exactly what it is meant for). 第二个版本使用
std::move
“重制”它为一个右值(这正是它的目的)。 Thus the copy ctor is avoided. 因此避免了复制控制器。
It's pretty reasonable to expect that a move will not be more expensive than a copy, so, given a real-life situation boiling down to this, you might prefer the second version. 可以预期,迁移的成本不会比复制的成本高,因此,考虑到现实生活中的情况,您可能更喜欢第二个版本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.