0

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.

  • 6
    Because you misinterpret what "move" means in C++11. When you move (in the sense of relocation), your address changes, too. But you move your furniture and all your stuff. That is basically what "move" in C++11 means, too. The address changes. It's a different object than the one you "move from". But the "internals" are moved from A to B. And by the way, `std::move` doesn't move. It makes the object "movable", i.e. you say to your compiler "I don't need `x` anymore. You don't need to copy its internals to `x1`, you can move them". – leemes Nov 10 '15 at 15:29
  • 1
    In addition to @leemes 's comment, take a look at NRTO (Named Return Value Optimisation). – OMGtechy Nov 10 '15 at 15:30

1 Answers1

5

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.

Community
  • 1
  • 1
TartanLlama
  • 63,752
  • 13
  • 157
  • 193