Is there a way to safely delete QList of non-unique pointers to MyObject?
I know this kind of question has been asked to death but I would like to know if there is anyway to do what I stated in the question without using Boost library pointers etc. Basically I have the following piece of cleanup code that deletes objects pointed to by the pointers in the double-dimension QList ( QList< QList > )
#include <QList>
QList< QList<MyObject*> > m_Data;
...
void CleanupMyObjectList开发者_Python百科
{
int numFrames = m_Data.size();
for(int i=0; i < numFrames; i++)
{
int numObjects = m_Data.at(i).size();
for(int j=0; j < numObjects; j++)
{
MyObject* removedObject = m_Data[i].at(j);
if(removedObject != NULL)
{
delete removedObject;//This assumes that the pointers are UNIQUE in this list!!! If not it will crash!!!
removedObject = NULL;
}
}
m_Data[i].clear();
}
m_Data.clear();
}
and it indeed crashes when I try to clean up the list populated by non-unique or shared (is this the correct term?) pointers, for example when m_Data[0][1] is equal to m_Data[1][1].
I know why it crashes so please save the explanation for that but rather I want to know if there is anyway to safely delete these objects with as little modification of the code as possible.
The easiest way is to create a temporary std::set<MyObject*>
. Iterate over m_Data, and instead of deleting the pointers straight away, add them to the set. Next, delete all pointers in the set. There are no duplicates in a std::set
.
You can safely delete a NULL
pointer. No need to check that
Because u don't want to use boost shared pointers ,
you can use QList< QList<QSharedPointer<MyObject>> > m_Data;
instead of QList< QList<MyObject*> > m_Data;
精彩评论