Search code examples
c++qtpointersdynamic-memory-allocation

Can Qt arrange for QObject* to be set to nullptr when QObject is destroyed?


Qt framework has an signal for all QObjects which is emmited before destruction of that QObject. This event can be used to have some QObject* variable automatically emptied when the object it points to is destroyed.

But to do this, you need to employ relatively lot of code. You would need to register a signal and link it up to the variable. Not very convenient in my opinion.

Can I have it arranged (by Qt) that a pointer to QObject is cleared automatically when QObject is destroyed?


Solution

  • Not with a raw pointer, no, but Qt supplies a templated QPointer class that does exactly what you are describing.