简体   繁体   English

Qt Raw vs std :: shared_ptr

[英]Qt raw vs std::shared_ptr

I noticed that when substituting raw pointers with shared_ptr in QT, my code does not work anymore. 我注意到在QT中用shared_ptr替换原始指针时,我的代码不再起作用。 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). 然后,程序崩溃或什么都不做(即使我稍后在代码中使用.get()函数从共享的指针获取原始指针)也是如此。 Does anybody knows what could be the cause? 有人知道是什么原因吗?

Using shared pointer with Qt model items causes an ownership conflict: QTreeWidget takes ownership of any QTreeWidgetItem you pass to it. 使用Qt模型项目使用共享指针会导致所有权的冲突: QTreeWidget采取任何的所有权QTreeWidgetItem您传递给它。 std::shared_ptr also owns its item. std::shared_ptr也拥有其项目。 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. 在这种情况下,如果Qt拥有指针的所有权(另一示例:父QObject拥有其子代的所有权),则不能同时使用std::shared_ptr / QSharedPointer std::shared_ptr only works well when using std::shared_ptr and std::weak_ptr exclusively to hold pointers to that particular object. 仅当仅使用std::shared_ptrstd::weak_ptr来保存指向该特定对象的指针时, std::shared_ptr才能很好地工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM