Qt list.clear() does it destroy the object's?

Niklas picture Niklas · May 26, 2014 · Viewed 8k times · Source

Let's say I have the following list:

QList<Type*> list;
list.add(new Type());
list.add(new Type());
list.add(new Type());
list.add(new Type());
list.add(new Type());
list.add(new Type());

If I want to empty the list, I can call list.clear()

Does it then automatically delete every pointer or do I have to do the following to prevent memory leaks:

foreach (Type* t, list) delete t;
list.clear();

Answer

lpapp picture lpapp · May 26, 2014

No, it just removes them from the list. You have to delete it on your own. Here can you find the implementation to make sure:

template <typename T>
Q_OUTOFLINE_TEMPLATE void QList<T>::clear()
{
    *this = QList<T>();
}

and here is the documentation saying that it only removes them from the list, but it is not deleting:

void QList::clear()

Removes all items from the list.

If you want to delete them, I suggest to use the following algorithm:

void qDeleteAll(ForwardIterator begin, ForwardIterator end)

Deletes all the items in the range [begin, end) using the C++ delete operator. The item type must be a pointer type (for example, QWidget *).

Example:

QList<Employee *> list;
list.append(new Employee("Blackpool", "Stephen"));
list.append(new Employee("Twist", "Oliver"));

qDeleteAll(list.begin(), list.end());
list.clear();