Appending pointers to QList

Routa picture Routa · Jul 15, 2010 · Viewed 15.6k times · Source

I need to insert pointers of classes (inherited from QObject) into a QList. I know that the following syntax can be used:

.h

QList<MyObject*> list;

.cpp

list.append(new MyObject("first", 1));
list.append(new MyObject("second", 2));
...

and then free memory:

if(!list.isEmpty())
{
    qDeleteAll(list);
    list.clear();
}

This should be valid and does not cause any memory leaks (as far as I know). However, I need to initialize objects before adding them to the collection. Can the following piece of code cause some errors like memory leaks or dangling pointers (I'll use the same way to delete pointers as above)?

MyObject *obj;

for(i = 0; i < 5; i++)
{   
    obj = new MyObject();
    if(!obj.Init(i, map.values(i)))
    {
        // handle error
    }
    else
    {
        list.append(obj);
    }
}

Thanks.

Answer

akira picture akira · Jul 15, 2010

if you take care of "obj" (the allocated but not initialized instance) in the "// handle error" case, your code is ok.