I'm new to computer science and I want to know if an object is being deleted if I heap allocate it and then for e. put it in a vector of pointer and then delete the vector. Will the heap object be gone? Here is an example of what I mean.
int main()
{
Type* someHeapObject = new Type();
vector<Type*> someVector(0);
someVector.push_back(someHeapObject);
}
So here's the main part: Can I delete the heap object with delete someVector[0]
, and then I DON'T have to delete it anymore like this: delete someHeapObject
CodePudding user response:
There are two things that you have to take care of:
Mistake 1
In delete [] someVector
you're using the delete []
form when you should be using the delete
form because you used the new
form and not the new[]
form for allocating memory dynamically. That is, delete [] someVector
is undefined behavior.
Mistake 2
The second thing that you must take care of is that you should not use two or more consecutive delete
's on the same pointer.
Now, when you wrote:
someVector.push_back(someHeapObject);
a copy of the pointer someHeapObject
is added to the vector someVector
. This means that now there are 2 pointers pointing to the same dynamically allocated memory. One pointer is the someHeapObject
and the second is the one inside the vector.
And as i said, now you should only use delete
on only one of the pointers. For example you can write:
delete someHeapOjbect; //now the memory has been freed
//YOU CAN'T USE delete someVector[0] anymore
Or you can write:
delete someVector[0]; //now te memory has been freed
//YOU CAN'T USE delete someHeapObject[0] anymore
Note that better option would be to use smart pointers instead explicitly doing memory management using new
and delete
.