PeeS
PeeS

Reputation: 1164

Deleting objects stored in std::vector

Just a quick small question :

#define SAFE_DELETE(p)    if((p))  { delete(p);    (p) =NULL; }
#define SAFE_DELETE_A(pa) if((pa)) { delete[](pa); (pa)=NULL; }

    // Add objects to our vector
    for(int a = 0; a< 150; a++)
    {
      CObject *pNewObject = new CObjectPlane(...)
      m_vpObjects.push_back(pNewObject);

    }


    // Delete all objects stored in our vector
    std::vector<CObject*>::iterator itObject;
    for(itObject = m_vpObjects.begin(); itObject!=m_vpObjects.end();)
    {
        SAFE_DELETE( (*itObject) );
        itObject = m_vpObjects.erase(itObject);
    }

    m_vpObjects.clear();

1) Will that remove objects stored in std::vector ( CObject* )

2) Is it safe to remove them this way ?

Upvotes: 0

Views: 210

Answers (2)

Tobias Langner
Tobias Langner

Reputation: 10808

Please do yourself a favor and store smart pointers (e.g. from boost or C++0x) instead of raw pointers inside a vector. This will also relief you from the burden of releasing them safely.

RAII (Resource Acquisition is Initialization) for the win!

Upvotes: 1

Nemo
Nemo

Reputation: 71525

It is safe but potentially (very) slow.

erase on the first element of a vector has to move all of the other elements of the vector, so your loop is O(n^2) in the size of the vector.

And there is no need to erase the elements since (a) they are pointers (no destructor) and (b) clear will do it anyway.

So:

for (itObject = m_vpObjects.begin(); itObject!=m_vpObjects.end(); ++itObject)
    SAFE_DELETE( (*itObject) );

P.S. There is nothing particularly "safe" about your SAFE_DELETE, but that is another topic.

P.P.S. if (p) delete p; is redundant.

Upvotes: 4

Related Questions