c++pointersc++11move-semanticsmemory-address

C++11: Does a move operation change the address?


Let's say that I have a main class SomeManager for keeping track of instances of another class SomeClass. When SomeClass is constructed it calls a method of SomeManager passing a pointer to itself. Then SomeManager takes that pointer and pushes it into a vector. The destructor of SomeClass calls another function of SomeManager which removes its pointer from the vector.

So, my question is. When an instance of SomeClass is moved through the move operator or constructor. Does its address change and I have to remove the old address and add the new one?

I have some ideas about this from what I've read but I'm not sure and I don't want to mess things up.


Solution

  • Short answer: no, the address of the moved from object doesn't change. But the old object may not be a useful state.

    When you perform a move construction you are creating a new object and moving the contents of another object into the new object. The new object will always be constructed in a different memory location from the old object. Something similar happens with move assignment: you simply move the contents of one object to another, but you still have to have two different objects at two different memory locations to perform the assignment (OK, there's self assignment, but we'll ignore that). The old object is still there (OK, it could be a temporary that gets destroyed at the end of the statement), but much of the time you have no guarantee about the old object except that it's in some valid state.

    An analogy may be a house filled with furniture. Move construction is like building a new house and moving the furniture to it. Move assignment is like buying a second preexisting home and moving the furniture to it. In both cases the new house has a different address from the old one, but the old one still exists. It just might not be in a useful state (hard to live in a house with no furniture!).