Search code examples
c++iteratordelete-operatorstd-pair

Deallocating memory of object inside a pair of a vector


I would like to know how to de-allocate memory of an object inside a pair of a vector.

vector< pair<int, object*> > vectorObject;

I did try using an iterator to iterate through all the elements, but I am unsure of how to delete an object that is inside a pair.

for (vector< pair<int, object*> >::iterator it = vectorObject.begin(); it != vectorObject.end(); ++it) {
    // delete?
}

Hopefully someone will be kind enough to advise!


Solution

  • `The straight answer is:

    for (vector< pair<int, object*> >::iterator it = vectorObject.begin(); it != vectorObject.end(); ++it) {
        delete it->second;
    }
    

    But. You should probably not be doing this.
    Having unmanged pointers is a BAD idea. You should change the type of the vector to use std::unique_ptr.

    vector< pair<int, std::unique_ptr<object>>>  vectorObject;
    

    This is because manually deleting objects is error prone and unless you take safeguards (by uisng RAII) NOT exception safe.