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

Say I have a core SomeManager class to track instances of another SomeClass class. When SomeClass is built, it calls the SomeManager method, passing it a pointer. Then SomeManager takes this pointer and inserts it into the vector. The SomeClass destructor calls another function SomeManager , which removes it from the vector.

So my question. When an instance of SomeClass moves through a move statement or constructor. Does it handle the change and do I need to delete the old address and add a new one?

I have some ideas about this from what I read, but I'm not sure, and I don't want to ruin anything.

+5
source share
3 answers

Short answer: no, the address of the moved object does not change. But the old facility may not be useful.

When you execute the move construct, you create a new object and move the contents of another object to the new object. A new object will always be built in another place of memory from the old object. Something similar happens with the destination of the move: you just move the contents of one object to another, but to complete the task you still need to have two different objects in two different memory cells (OK, there is a self-start, but we will ignore it), the Old object is all still exists (OK, it can be temporary, which is destroyed at the end of the instruction), but most of the time you have no guarantee regarding the old object, except that it is in some acceptable condition.

An analogy can be a house filled with furniture. The construction movement is like building a new house and moving furniture to it. Moving a destination is like buying a second existing home and moving furniture to it. In both cases, the new house has a different address from the old one, but the old one still exists. It may not be in good condition (it’s hard to live in a house without furniture!).

+16
source

Yes. The move operator and assignment operator help the new SomeClass instance take ownership of the state of the old instance, but the new instance has a separate address.

One of the considerations for you is the question of whether you want the remove-from SomeClass β€œregistered” itself from SomeManager , because it was moving due to expectations of destruction, regardless of whether it depends on your exact code.

+3
source

Moving essentially means: "Here is object X. Create a new object Y by stealing the interiors of X." Likewise, to assign movement. You are not moving the object; you move its contents.

The address of the moved object X does not change. Its contents can change (for example, become empty) or cannot (for example, if it is a primitive type for which the move is a copy).

Although in the circuit you are describing, it is better to make sure that the move constructor also registers the object being created ...

+3
source

Source: https://habr.com/ru/post/1213292/


All Articles