Reputation: 941
Given is the following C++ code:
std::vector<int> myVec;
int* num = new int(1);
myVec.emplace_back(std::move(*num));
If a move a variable with dynamic storage duration into a container (e.g. a vector) is it still necessary to delete num
manually if myVec
is destroyed (goes out of scope)? Is there any difference if I use push_back
instead of emplace_back
?
Upvotes: 5
Views: 1390
Reputation: 50550
You are copying the value stored in *num
in your vector.
It is not much different from doing this:
int* num = new int(1);
int cpy = *num;
Therefore yes, you must delete it.
Vectors do not magically handle lifetimes of objects when dealing with pointers somehow in your code.
You can use unique_ptr
s if you want to have controlled lifetimes for your objects:
myVec.emplace_back(std::make_unique<int>(1));
Anyway, this requires you to 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);
Allocated memory will be freed as soon as num
goes out of its scope.
Upvotes: 3
Reputation: 48625
In your case a move will not occur because you are using a primitive type int
which will simply be copied.
But even when you move the value of an object on the heap into a vector you still need to release the memory because moving the value still leaves the moved from object in a valid state. It still exists and can be used. The effect of moving is that its value may have changed and so its value can't be relied on until you re-assign an new one.
It doesn't matter if you use emplace_back()
or push_back()
to move the value it still remains as a valid object on the heap so i still needs deleting independently of what happens to the moved to element in the vector.
So std::move()
facilitates (but does not guarantee) moving the contents (or value) of the object - not the object itself so the moved from object still needs deleting.
Upvotes: 3