QSharedPointer and QObject::deleteLater

旧时模样 提交于 2019-12-22 04:13:07

问题


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

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?


回答1:


You can use the QSharedPointer constructor with the Deleter :

The deleter parameter specifies the custom deleter for this object. The custom deleter is called, instead of the operator delete(), when the strong reference count drops to 0. This is useful, for instance, for calling deleteLater() on a QObject instead:

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



回答2:


An alternative is using QPointer instead of QSharedPointer, citing the documentation:

The QPointer class is a template class that provides guarded pointers to QObject.

A guarded pointer, QPointer, behaves like a normal C++ pointer T *, except that it is automatically set to 0 when the referenced object is destroyed (unlike normal C++ pointers, which become "dangling pointers" in such cases). T must be a subclass of QObject.



来源:https://stackoverflow.com/questions/12623690/qsharedpointer-and-qobjectdeletelater

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