If Qt code cannot delete your pointer, then you can use std::shared_ptr
and std::weak_ptr
to help you track of these things.
#include <iostream>
#include <memory>
struct Foo { int a; };
int main()
{
std::shared_ptr<Foo> shared = std::make_shared<Foo>();
std::weak_ptr<Foo> weak = shared;
std::cout << "is valid?: " << (bool)shared << weak.expired() << std::endl;
shared.reset(); // delete the pointer
std::cout << "is valid?: " << (bool)shared << weak.expired() << std::endl;
return 0;
}
results in,
is valid?: 10
is valid?: 01
meaning after the shared_ptr releases its allocated data, the weak_ptr expires as well (expired returns true).
Qt has similar classes to help you. QSharedPointer, QWeakPointer, etc. If you need to keep track if a QObject pointer is deleted, you should use QPointer
http://qt-project.org/doc/qt-5/QPointer.html
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.
for example,
#include <QCoreApplication>
#include <QDebug>
#include <QPointer>
int main(int a, char *b[])
{
QCoreApplication app(a,b);
QObject *obj1 = new QObject;
QObject *obj2 = new QObject(obj1);
QPointer<QObject> o(obj2);
qDebug() << o.isNull();
delete obj1;
qDebug() << o.isNull();
return 0;
}
results in,
false
true
As you can see, the child QObject pointer is invalidated.