Qt Raw vs std :: shared_ptr [英] Qt raw vs std::shared_ptr

查看:134
本文介绍了Qt Raw vs std :: shared_ptr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到在QT中用shared_ptr替换原始指针时,我的代码不再起作用。
例如,如果不是

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));

我使用

 std::shared_ptr<QTreeWidgetItem> vItem(new QTreeWidgetItem(ItemTitle));

然后,程序崩溃或什么也没做(即使我使用.get()函数从我的代码后面的共享指针中获取
原始指针)。有人知道是什么原因吗?

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?

推荐答案

在Qt模型项中使用共享指针会导致所有权冲突: QTreeWidget 获取您传递给它的任何 QTreeWidgetItem 的所有权。 std :: shared_ptr 也拥有它的物品。两者都假定他们可以自己删除该项目,没有其他人可以将其删除。

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.

在这种情况下,Qt拥有指针的所有权(另一个示例:parent) QObject 拥有其子代的所有权),则不能使用 std :: shared_ptr / QSharedPointer 同时。 std :: shared_ptr 仅在使用 std :: shared_ptr std :: weak_ptr时才能很好地工作专门用于保存指向该特定对象的指针。

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.

这篇关于Qt Raw vs std :: shared_ptr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆