I just want to make sure if this is the right way to delete an allocated memory where there exist an element in the vector that pointing to that object;
vector<Fruit*> temp;
let say if the sixth element in the vector is pointing to the object that I want to delete.
Fruit* a = temp[5];
temp.erase(temp.begin()+5);
delete a;
is this right? thx
The Kerrek's suggestion is of course OK:
delete temp[5];
temp.erase(temp.begin() + 5);
I'm writing an answer, however, to suggest you think about smart pointers. Here's an example:
std::vector<std::shared_ptr<Fruit>> v;
// add some elements
v.erase(temp.begin() + 5);
In this case, there's no memory leak, because shared_ptr destruction deletes the object owned by it, or decreases the number of references properly. If there's no shared ownership involved, you can just use unique_ptr. boost::ptr_vector might also come in handy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With