Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

deleting an element in a vector of pointer

Tags:

c++

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

like image 382
Nick Stov Avatar asked Dec 17 '25 18:12

Nick Stov


1 Answers

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.

like image 149
Bartek Banachewicz Avatar answered Dec 20 '25 06:12

Bartek Banachewicz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!