سؤال

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 QStringList that the QTreeWidgetItem maintains will be deleted with the tree item - that's going to work fine.

But the temp you're allocated will not. When you pass that *temp to 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:

while(other_elements)
{
    QStringList temp;
    temp.push_back("first_field");
    temp.push_back("second_field");

    items.append(new QTreeWidgetItem((QTreeWidget*)0, temp));

    element_iterator++;
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top