How to free an element in a pointer vector?

So, I have a pointer vector like:

vector<Example*> ve; 

I fill this vector with such pointers

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

But when I want to remove them, how can I assure them of their release? is that enough?

 ve.erase(ve.begin() + 1) delete ve[1] 
+6
source share
2 answers

You should do it the other way around, of course:

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

However, it is much more preferable to use smart pointers (for example, std::unique_ptr ) instead of raw pointers when expressing ownership.

+8
source

You need to remove the pointers before erasing the vector:

 for (vector<Example *>::iterator it = vec.begin(); it != vec.end(); it++) { delete *it; } vec.clear(); 
+1
source

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


All Articles