Reputation: 41
I am learning about c++ and I need a little advice on how to clean up memory when not using pointers.
I have a background Blackberry 10 app which has a memory limit of 3MB before it gets stopped, my app is being stopped because of hitting this limit and I am having trouble finding figuring out why.
I have narrowed down the increasing of memory to a function - if I don't call this function the memory doesn't increase.
The function uses QVariant, QVariantList, QVariantMap, QString which are declared outside the function when the class is created (i.e QVariantMap map), before I access these objects in the function I call .clear() on each of them which I am of the understanding should clean up the memory held, I am also using int in the function which are also declared outside of it.
The function is quite large and is calling other functions so I have provided a snippet below of what I am doing in case it is obviously wrong to others.
bindings.clear();
bindings["name"] = name;
result.clear();
result = sqlda->execute(sqlQueryz, bindings);
if (!sqlda->hasError()) {
if( !result.isNull() ) {
list.clear();
list = result.value<QVariantList>();
recordsRead = list.size();
for(int iii = 0; iii < recordsRead; iii++) {
map.clear();
map = list.at(iii).value<QVariantMap>();
Any help appreciated.
Upvotes: 4
Views: 366
Reputation: 2020
calling .clear() on a QList or on a QMap clears the list but does not free the objects in the list, so for example if you have:
QList<QObject *> list;
QObject *c = new QObject();
c->setObjectName("object_a");
list.append(c);
QObject *b = new QObject();
b->setObjectName("object_b");
list.append(b);
qDebug() << list.count(); //here you get 2
list.clear();
qDebug() << list.count(); //here you get 0;
qDebug() << a->objectName(); // Here you get "object_a"
This means that after the .clear() your ojects are still living in memory
What you should do when you want to really get rid of all the objects in the list is:
while (list.count() > 0)
delete list.takeFirst();
and here list.clear() is redundant.
Upvotes: 1