QSharedPointer and QObject :: deleteLater

I have a situation where the QSharedPointer managed entity signals that it has completed its assignment and is soon ready to be deleted (after execution left the function emitting my readyForDeletion signal). When working with regular pointers, I simply call QObject::deleteLater on the object, however this is not possible with the QSharedPointer -managed instance. My workaround is this:

 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 when using this method there is a lot of overhead (allocating a new QObject , etc.). Is there a better solution to handle such situations?

+4
source share
2 answers

You can use the QSharedPointer constructor

+13
source

An alternative is QPointer instead of QSharedPointer , referring to the documentation:

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

The protected QPointer pointer behaves like a regular C ++ T * pointer, except that it automatically sets to 0 when the link object is destroyed (unlike ordinary C ++ pointers, which in such cases become "dangling pointers"). T must be a subclass of QObject.

0
source

Source: https://habr.com/ru/post/1436630/


All Articles