Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deallocate an element in a vector of pointers?

So I have a vector of pointers like so:

vector<Example*> ve;

I fill this vector with pointers like this

Example* e = new Example();
ve.push_back(e)

But when I want to remove them, how do I assure they get deallocated? Is this enough?

ve.erase(ve.begin() + 1)
delete ve[1]
like image 934
rinti Avatar asked May 14 '13 12:05

rinti


People also ask

How do you remove an element from the end of a vector?

pop_back() function is used to pop or remove elements from a vector from the back. The value is removed from the vector from the end, and the container size is decreased by 1.

Do you have to deallocate pointers?

No. The only exception to that would be if deltaTime was created with new and it was the responsibility of Update to return the memory (unlikely, and a poor design). like you would with any other pointer? Just because something is a pointer does not mean you should call delete .


1 Answers

You have to do it the other way round, of course:

delete ve[1];
ve.erase(ve.begin() + 1);

However, it's vastly more preferable to use smart pointers (such as std::unique_ptr) instead of raw pointers when expressing ownership.

like image 161
Angew is no longer proud of SO Avatar answered Nov 14 '22 21:11

Angew is no longer proud of SO