Qt raw vs std::shared_ptr

穿精又带淫゛_ 提交于 2019-12-23 12:13:10

问题


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?


回答1:


Using shared pointer with Qt model items causes an ownership conflict: QTreeWidget takes ownership of any QTreeWidgetItem you pass to it. std::shared_ptr also 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 QObject taking ownership of its children), one cannot use std::shared_ptr/QSharedPointer at the same time. std::shared_ptr only works well when using std::shared_ptr and std::weak_ptr exclusively to hold pointers to that particular object.



来源:https://stackoverflow.com/questions/13876835/qt-raw-vs-stdshared-ptr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!