测试代码如下:
// a.h
#ifndef A_H
#define A_H
#include <QObject>
#include <QDebug>
class A : public QObject
{
Q_OBJECT
public:
explicit A(QObject *parent = nullptr);
~A();
void print();
int a;
signals:
};
class B : public QObject
{
public:
explicit B(QObject *parent = nullptr);
~B();
A *a;
};
#endif // A_H
// a.cpp
#include "a.h"
A::A(QObject *parent) : QObject(parent)
{
a = 10;
}
A::~A()
{
qDebug() << "This is A destructor...";
}
void A::print()
{
//下面这两行,同时存在时,程序会出现段错误
//这句单独存在时,此函数无效
qDebug() << "This is A print method, a = " << a;
//这句单独存在时,可以完美执行,打印能够完成
qDebug() << "This is A print method;";
}
B::B(QObject *parent) : QObject(parent)
{
a = new A(this);
}
B::~B()
{
qDebug() << "This is B destructor....";
}
// main.cpp
#include <QCoreApplication>
#include "a.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
B *b = new B();
qDebug() << "b delete start";
delete b;
qDebug() << "b delete end";
A *c = b->a;
c->print();
return a.exec();
}
/*
* 执行结果为:
* b delete start
* This is B destructor....
* This is A destructor...
* b delete end
* This is A print method;
*/
执行结果说明了,继承自QObject的对象,在使用了 Q_OBJECT 宏之后,父对象(通过parent关联,并非继承关系)在被析构时,其子对象会一并析构。