在本例中,移动语义是如何工作的:
struct test {
int ii[10];
int i;
};
test f() {
test a;
std::cout << "[1] " << &a << std::endl;
return a;
}
int main()
{
test x (f());
std::cout << "[2] " << &x << std::endl;
test x1 (std::move(x));
std::cout << "[3] " << &x1;
}输出:
[1] 0x7fff50ac70c0
[2] 0x7fff50ac70c0
[3] 0x7fff50ac70f0为什么x是使用f()的返回值构造的,但是x1的地址与x不同?
编辑
struct test {
std::string s;
}
[...]
std::cout << (*void)&x.s[0];我想我终于明白了。现在地址是一样的。
发布于 2015-11-10 15:31:16
这与移动语义没有任何关系。a和x具有相同的内存地址,因为副本是https://stackoverflow.com/questions/12953127/what-are-copy-elision-and-return-value-optimization,因此直接在调用站点上分配f的返回。x1不具有与x相同的地址,因为它是一个单独的对象,而单独的对象不能具有相同的地址。移动不会改变地址,它允许您的对象的内脏被撕开并自带到移动对象中。
https://stackoverflow.com/questions/33633473
复制相似问题