Search code examples
c++qtpointersqlist

Appending pointers to QList


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.


Solution

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