Rob Dhaliwal Rob Dhaliwal - 1 month ago 10
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

my_vect.clear()


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++)
{
new_my_vect.push_back(&my_vect[i]);
}

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


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

Thank-you,

Answer

You should be adding objects as follows

vector<Object> my_vect;

my_vect.emplace_back();

or

my_vect.push_back(Object());

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.