Say I have a class
MyClass {
//.. cstors and dstor
void MyClass(MyClass&& source) : some_obj_(std::move(source.some_obj_));
SomeObj some_obj_;
}
Say I do the following:
// a1 is defined somewhere else with a wider scope
MyClass a1;
...
// a2 is defined locally and will go out of scope soon
MyClass a2;
... //Populate a2's some_obj_ field with data
a1 = std::move(a2); // move instead of copy
In this case, the move constructor will be invoked. From what I understand, the move constructor swaps the field pointers between the two so that no copy happens.
So here comes my question. When a2
is instantiated, it allocates memory within a2
itself for field some_obj_
. When the move happens, we swap the pointers so that now a1
's some_obj_
points to the chunk of memory that a2
holds (instead of copying it over its own memory space). In the future, when a2
goes out of scope, e.g. function containing a2
returns so the stack frame is cleaned up, since a2.some_obj_
resides within a2
, it also gets deleted. Since a1.some_obj_
, after the move, points to a2
's memory that has been cleaned now, does a1
lose that part of the information?
It seems that following the above logic, a1
will now pointing to invalid memory space.
Aucun commentaire:
Enregistrer un commentaire