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();
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:
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();