Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 463
Routa Avatar asked Jul 15 '10 10:07

Routa


2 Answers

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

like image 151
akira Avatar answered Nov 14 '22 22:11

akira


Use QSharedPointer instead.

QList<QSharedPointer<MyObject> > list;

To free memory you only have to do

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

To append to list

list.append(QSharedPointer<MyObject>(new MyObject("first", 1)));
list.append(QSharedPointer<MyObject>(new MyObject("second", 2)));
like image 4
PBareil Avatar answered Nov 14 '22 20:11

PBareil