Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do delete items in a vector if using remove_if and items are pointers to objects?

I fear that I am running into memory leak issues by doing the following:

(Sample code)

class myItem //random container stuff mostly. All primatives.
{
    int index;
    char* name;
    int val1;
    int val2;
};

class vecList
{

    vector< myitem* > *myVec;

    void delete()
    { 
        MyVec->erase(std::remove_if(myVec->begin(), MyVec->end(), IsMarkedToDelete), MyVec->end()); //leak here?
    }
};

Erase doesn't free the memory if it's a pointer, right? If I wasn't using remove_if, I could call delete on the pointer before destroying it. How would I do it in this case? Smart Pointers? I'd prefer not to re-implement everything with them and I don't really want to add the boost library.

Thanks!

like image 519
Jordan Avatar asked Mar 02 '26 09:03

Jordan


1 Answers

You could just delete the item in your IsMarkedToDelete function when it returns true.

like image 90
Xeo Avatar answered Mar 04 '26 22:03

Xeo



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!