I noticed that when substituting raw pointers with shared_ptr in QT, my code does not work anymore.
For example, if instead of
QTreeWidgetItem* vItem(new QTreeWidgetItem(ItemTitle));
I use
std::shared_ptr<QTreeWidgetItem> vItem(new QTreeWidgetItem(ItemTitle));
then, either the program crashes or nothing is done (even if I use the .get() function to get the
raw pointer from the shared one later in my code). Does anybody knows what could be the cause?
Using shared pointer with Qt model items causes an ownership conflict:
QTreeWidgettakes ownership of anyQTreeWidgetItemyou pass to it.std::shared_ptralso owns its item. Both assume they can delete the item themselves and that nobody else will delete it behind their back.In such situations, where Qt takes ownership of the pointers (other example: parent
QObjecttaking ownership of its children), one cannot usestd::shared_ptr/QSharedPointerat the same time.std::shared_ptronly works well when usingstd::shared_ptrandstd::weak_ptrexclusively to hold pointers to that particular object.