QObject的对象树析构机制简单验证

测试代码如下:

// 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关联,并非继承关系)在被析构时,其子对象会一并析构。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值