0

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?

Daniel Hedberg
  • 5,677
  • 4
  • 36
  • 61
Johnny Pauling
  • 12,701
  • 18
  • 65
  • 108
  • to avoid this you can use the overloaded `operator<<` to do that you just call `items.append(new QTreeWidgetItem(0, QStringList() << "first_field" << "second_field");` soo long zai – Zaiborg Jan 28 '13 at 08:51

1 Answers1

4

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++;
}
Jeremy Friesner
  • 70,199
  • 15
  • 131
  • 234
Mat
  • 202,337
  • 40
  • 393
  • 406