When I insert elements into a QTreeWidget, I allocate memory for both QStringList and QTreeWidgetItem
QStringList *temp;
while(other_elements)
{
temp = new QStringList();
temp->push_back("first_field");
temp->push_back("second_field");
items.append(new QTreeWidgetItem((QTreeWidget*)0, *temp));
element_iterator++;
}
myTreeWidget->insertTopLevelItems(0, items);
I read that QTreeWidgetItem is automatically deallocated when the clear() function is called, but what about the QStringList? Is it a memory leak?
Your code will leak, but not for the reason you think.
The
QStringListthat theQTreeWidgetItemmaintains will be deleted with the tree item – that’s going to work fine.But the
tempyou’re allocated will not. When you pass that*tempto the constructor, the item stores a copy of that. The object you allocated is still alive and well after the constructor call – and since you’re not deleting it, it is leaked.Change your code to the following to avoid the leak and unnecessary heap allocation: