本文介绍了QSharedPointer 和 QObject::deleteLater的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种情况,QSharedPointer 托管对象表示它已经完成了它的目的并且准备好很快删除(执行后离开函数发出我的 readyForDeletion 信号).当使用普通指针时,我只需要在对象上调用QObject::deleteLater,但是使用QSharedPointer是不可能的-托管实例.我的解决方法如下:

I have a situation where a QSharedPointer managed object signalizes that it has finished it's purpose and is ready for deletion soon (after execution left the function emitting my readyForDeletion signal). When working with normal pointers, I'd just call QObject::deleteLater on the object, however this isn't possible with a QSharedPointer-managed instance. My workaround is the following:

template<typename T>
class QSharedPointerContainer : public QObject
{
   QSharedPointer<T> m_pSharedObj;

public:

   QSharedPointerContainer(QSharedPointer<T> pSharedObj)
      : m_pSharedObj(pSharedObj)
   {} // ==> ctor

}; // ==> QSharedPointerContainer

template<typename T>
void deleteSharedPointerLater(QSharedPointer<T> pSharedObj)
{
   (new QSharedPointerContainer<T>(pSharedObj))->deleteLater();
} // ==> deleteSharedPointerLater

这很有效,但是使用这个方法有很多开销(分配一个新的 QObject 等等).有没有更好的解决方案来处理这种情况?

This works well, however there's a lot of overhead using this method (allocating a new QObject and so on). Is there any better solution to handle such situations?

推荐答案

您可以使用 QSharedPointer 构造函数 带有 Deleter :

You can use the QSharedPointer constructor with the Deleter :

deleter 参数指定此对象的自定义删除器.调用自定义删除器,而不是操作符 delete(),当强引用计数下降到 0.这很有用,例如,用于在 QObject 上调用 deleteLater():

 QSharedPointer<MyObject> obj =
         QSharedPointer<MyObject>(new MyObject, &QObject::deleteLater);

这篇关于QSharedPointer 和 QObject::deleteLater的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-29 14:31
查看更多