Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Will a heap allocatet object get delete when i assign it to a vector and then delete the vector?

im new to computer science and i want to know if a object is being deletet 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 a example what i mean.

int main()
{
   Type* someHeapObject = new Type();
   
   vector<Type*> someVector(0);

   someVector.push_back(someHeapObject);
}

So heres the main part: Can i delete the heap object with delete someVector[0] , and then i DONT have to delete it anymore like this: delete someHeapObject

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading