Reputation: 63
How does move semantics work in this example:
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;
}
Output:
[1] 0x7fff50ac70c0
[2] 0x7fff50ac70c0
[3] 0x7fff50ac70f0
Why x was constructed using return value from f(), but x1 got different address than x?
Edit
struct test {
std::string s;
}
[...]
std::cout << (*void)&x.s[0];
I think I've understood eventually. Now addresses are the same.
Upvotes: 0
Views: 94
Reputation: 65600
This doesn't really have anything to do with move semantics. a
and x
have the same memory address because the copy is elided, so the return of f
is allocated directly at the call site. x1
does not have the same address as x
because it is a separate object, and separate objects cannot have the same address. Moving doesn't change the address, it allows the guts of your object to be ripped out and sellotaped into the moved-to object.
Upvotes: 5