问题描述
#include <iostream>
struct Foo{
int i = 10;
};
Foo useless_move(Foo &&f){
return f;
}
int main() {
Foo f = Foo();
f.i = 100;
Foo f1 = useless_move(std::move(f));
std::cout << f.i;
std::cout << f1.i;
}
为什么我仍然可以访问f, c $ c> Foo f1 = useless_move(std :: move(f)); 我没有将所有权从f转移到f1吗?
Why can I still access f, after I have moved the value with Foo f1 = useless_move(std::move(f));
Didn't I transfer the ownership from f to f1?
推荐答案
写 std :: move
不会神奇地发生移动;它在这个意义上真正命名。它所做的是给你一个右值引用。
Writing std::move
doesn't magically make a move happen; it's really badly named in that sense. All it does is give you an rvalue reference.
当你通过一个移动构造函数传递一个对象的右值引用时发生移动,该构造函数被写为交换间接资源例如容器和文件句柄,而不是深度复制它们(或根本没有正确地复制它们)。
Moves happen when you are passing around an rvalue reference to an object with a move constructor, which is written to swap indirect resources such as containers and file handles rather than deep copying them (or failing to properly copy them at all).
在这种情况下,你只有一个 int
。
没有移动构造函数,没有移动,也没有执行移动。
In this case, you just have an int
.
There's no move constructor, nothing to move, and no move performed.
并且即使有,刚刚移动的对象的状态是未指定的,不保证为…好吧,不管你期望的是什么。
And even if there were, the state of an object that has just been moved from is unspecified, not guaranteed to be … well, whatever it is that you were expecting instead.
这篇关于为什么仍可以访问已移动的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!