Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QSharedPointer and QObject::deleteLater

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?

like image 581
athre0z Avatar asked Sep 27 '12 14:09

athre0z


2 Answers

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);
like image 171
pnezis Avatar answered Oct 07 '22 22:10

pnezis


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.

like image 23
vlp Avatar answered Oct 07 '22 23:10

vlp