Moving a dynamically allocated variable to a vector

The following C ++ code is provided:

std::vector<int> myVec; int* num = new int(1); myVec.emplace_back(std::move(*num)); 

If you move a variable with dynamic storage duration to a container (for example, a vector), do you still need to delete num manually if myVec is destroyed (out of scope)? Is there any difference if I use push_back instead of emplace_back ?

+5
source share
2 answers

You copy the value stored in *num in your vector.
This is not much different from this:

 int* num = new int(1); int cpy = *num; 

So yes, you have to delete it.
Vectors do not magically process the lifetimes of objects when working with pointers somehow in your code.


You can use unique_ptr if you want to control the lifetime for your objects:

 myVec.emplace_back(std::make_unique<int>(1)); 

In any case, this requires that you change the type of the vector from std::vector<int> to std::vector<std::unique_ptr<int>> .

Otherwise, you can do this:

 std::vector<int> myVec; auto num = std::make_unique<int>(1); myVec.emplace_back(*num); 

The allocated memory will be freed as soon as num goes out of scope.

+3
source

In your case, the transition will not happen, because you are using a primitive int type that will just be copied.

But even when you move the value of an object in a heap to a vector, you still need to free up memory, because moving the value still leaves the moved from the object in an acceptable state. It still exists and can be used. The effect of the move is that its value can change, and therefore its value cannot be relied on until you reinstall the new one.

It doesn't matter if you emplace_back() or push_back() to move the value that it still remains as a valid object on the heap, so I still need to delete it no matter what happens with the moved item in the vector.

So, std::move() facilitates (but does not guarantee) the movement of the content (or value) of the object - not the object itself, so it still needs to be removed from the object.

+2
source

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


All Articles