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.
if you take care of "obj" (the allocated but not initialized instance) in the "// handle error" case, your code is ok.
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)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With