[英]std::move on a C++ class does not move all members?
I understand that using v.push_back(std::move(foo))
will move foo contents to a vector. 我了解使用v.push_back(std::move(foo))
会将foo内容移至向量。
However I do not understand why the below code : 但是我不明白为什么下面的代码:
#include <iostream>
#include <vector>
struct Foo {
std::string s;
float f;
friend std::ostream& operator<<(std::ostream& stream,const Foo& foo) {
stream << "{" << foo.s << ":" << foo.f << "}";
return stream;
}
};
int main() {
Foo foo{"Hello",2.0f};
std::vector<Foo> v;
v.push_back(foo);
std::cout << foo << std::endl;
v.push_back(std::move(foo));
std::cout << foo << std::endl;
std::cout << v[0] << v[1] << std::endl;
}
produces this output : 产生此输出:
{Hello:2}
{:2}
{Hello:2}{Hello:2}
Why 2 is not "moved" ? 为什么2不被“感动”?
You create a variable foo
您创建一个变量foo
Foo foo{"Hello",2.0f};
Then declare a vector 然后声明一个向量
std::vector<Foo> v;
Then call push_back
which invokes a copy of your Foo
然后调用push_back
,它调用Foo
的副本
v.push_back(foo);
std::cout << foo << std::endl;
Then you std::move(foo)
, which invalidates your foo
instance 然后您std::move(foo)
,这会使您的foo
实例无效
v.push_back(std::move(foo));
Trying to cout
foo
is now undefined behavior, as the internals are may be garbage. 试图cout
foo
现在是不确定的行为,因为内部有 可能是垃圾。
std::cout << foo << std::endl;
While you technically could std::move
a primitive, most implementations will simply invoke a copy because it is cheaper and faster . 从技术上讲,您可以 std::move
原语,但是大多数实现将仅调用副本,因为它更便宜,更快捷 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.