Rob Dhaliwal Rob Dhaliwal - 8 months ago 37
C++ Question

Free Memory from Vector of Objects (not ptrs to the objects)

I declared the vector:

vector<Object> my_vect;

and I pushed some objects into it like

my_vect.push_back(*(new Object()));

I know it would have been simple if I were to declare a vector of pointers, but this is crucial to my code.

I tried using


But to no avail.

Moreover, I also tried getting the pointers to the objects like:

vector<*Object> new_my_vect;

for(int i = 0; i < my_vect.size(); i++)

for(int i = 0; i < new_my_vect.size(); i++)
delete new_my_vect[i];

But I get an "
free(): invalid pointer:
" error.



You should be adding objects as follows

vector<Object> my_vect;




I would not recommend getting pointers to the objects within the vector, as if anything causes the vector to re-allocate those pointers will be invalidated as the underlying array will be copied elsewhere.