Search code examples
c++qtshared-ptrqobjectqsharedpointer

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?


Solution

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