Hello!
I recently started investigating Qt for myself and have the following question:
Suppose I have some QTreeWidget* widget
. At some moment I want to add some items to it and this is done via the following call:
QList<QTreeWidgetItem*> items;
// Prepare the items
QTreeWidgetItem* item1 = new QTreeWidgetItem(...);
QTreeWidgetItem* item2 = new QTreeWidgetItem(...);
items.append(item1);
items.append(item2);
widget->addTopLevelItems(items);
So far it looks ok, but I don't actually understand who should control the objects' lifetime. I should explain this with an example:
Let's say, another function calls widget->clear();
. I don't know what happens beneath this call but I do think that memory allocated for item1
and item2
doesn't get disposed here, because their ownage wasn't actually transfered. And, bang, we have a memory leak.
The question is the following - does Qt
have something to offer for this kind of situation? I could use boost::shared_ptr
or any other smart pointer and write something like
shared_ptr<QTreeWidgetItem> ptr(new QTreeWidgetItem(...));
items.append(ptr.get());
but I don't know if the Qt itself would try to make explicit delete
calls on my pointers (which would be disastrous since I state them as shared_ptr
-managed).
How would you solve this problem? Maybe everything is evident and I miss something really simple?