Reputation: 761
I am facing a strange problem in my code trying to deleting a QTreeWidgetItem
. In particular, I have this in my class:
std::map<int, std::unique_ptr<QTreeWidgetItem>> mymap;
When I close my application, I have a SegFault, inside the default destructor of the unique_ptr
. Then, I try to decompose the problem, and I create a destructor that does the following:
~MyClass() {
for ( auto x = mymap.begin(); x != mymap.end(); x++ ) {
QTreeWidgetItem* temp = x->second.release();
qDebug() << "make sure the pointer is not broken " << temp->isDisabled();
delete temp;
}
}
The call to the function isDisabled()
is useless, just to make sure that the pointer is not broken. Well, then I can use the object in the pointer, but when I try to delete it, I have the SegFault.
Any suggestion? Thanks to everybody
Upvotes: 0
Views: 532
Reputation: 3143
QTreeWidgetItems
are designed to be owned by QTreeWidget
. As the documentation says, in the destructor of QTreeWidget
all of its items are deleted. Having a std::unique_ptr
to QTreeWidgetItem
existing within QTreeWidget
created the second independent ownership of QTreeWidgetItem
and hence leads to double deletion of the same pointer. In your example the crash happens because by the moment of manual deletion the pointer has already been deleted along with QTreeWidget
holding it.
Calling temp->isDisabled()
does not really check for the pointer's validity: if the pointer has already been deleted, such a call just yields undefined behaviour - the app may crash or it may not.
Upvotes: 1