简述:
所有继承自QObject的类都被对象树管理,自动释放内存;
实现:
重写QObject构造函数
#ifndef QTEST10_A_H
#define QTEST10_A_H
#include "QObject"
#include <iostream>
class A :public QObject{
public:
explicit A(QObject *parent= nullptr) : QObject(parent) {}
void out(){
std::cout<<"A\n";
}
};
#endif //QTEST10_A_H
#ifndef QTEST10_B_H
#define QTEST10_B_H
#include "QObject"
#include <iostream>
class B :public QObject{
public:
explicit B(QObject *parent= nullptr) : QObject(parent) {}
void out(){
std::cout<<"B\n";
}
~B() override {
std::cout<<"b destroy\n";
}
};
#endif //QTEST10_B_H
main:
#include <QCoreApplication>
#include "A.h"
#include "B.h"
int main(int argc,char **argv) {
QCoreApplication app(argc,argv);
auto a=new A();
auto b=new B(a);
delete a;
return 0;
}
When QObjects are created on the heap (i.e., created with new), a tree can be constructed from them in any order, and later, the objects in the tree can be destroyed in any order. When any QObject in the tree is deleted, if the object has a parent, the destructor automatically removes the object from its parent. If the object has children, the destructor automatically deletes each child. No QObject is deleted twice, regardless of the order of destruction.
conclusion:
Qt的内存管理
评论区