Qt:解构过程中的儿童生活对象
Qt: Child QObject during deconstruction?
当父QObject被解构时,它的子对象什么时候被解构?例如:
QChild* child = new QChild(master);
当我们删除master时;主的析构函数~master()将在子的析构符之前或之后调用?这里有什么秩序?
~QObject()
将删除所有子项,准确的顺序可以在源代码中找到。考虑Qt源代码:
QObject::~QObject()
{
Q_D(QObject);//now we have d-pointer
//...
//another code here, which for example disconnect everything
if (!d->children.isEmpty())
d->deleteChildren();
//...
}
其中deleteChildren()
为:
void QObjectPrivate::deleteChildren()
{
const bool reallyWasDeleted = wasDeleted;
wasDeleted = true;
// delete children objects
// don't use qDeleteAll as the destructor of the child might
// delete siblings
for (int i = 0; i < children.count(); ++i) {
currentChildBeingDeleted = children.at(i);
children[i] = 0;
delete currentChildBeingDeleted;
}
children.clear();
currentChildBeingDeleted = 0;
wasDeleted = reallyWasDeleted;
}
另请参阅:http://www.programmerinterview.com/index.php/c-cplusplus/execution-order-of-constructor-and-destructor-in-inheritance/
另一个例子:
#include <QApplication>
#include <QDebug>
class Child: public QObject
{
public:
Child(QObject *parent = 0) : QObject(parent)
{}
~Child()
{
qDebug("child destroyed");
}
};
class Parent: public QObject
{
public:
Parent(QObject *parent = 0) : QObject(parent)
{}
~Parent()
{
qDebug("do something here");
qDebug("parent destroyed");
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Parent *parent = new Parent;
Child *child1 = new Child(parent);
Child *child2 = new Child(parent);
//do something
delete parent;
return a.exec();
}
输出:
do something here
parent destroyed
child destroyed
child destroyed
如果您将编写~Parent(){delete A; delete B;}
,那么正如您从输出中看到的,A
和B
将首先被删除,子对象将更早被删除。
为什么
因为我之前建议你的规则
Inside Base constructor
Inside Derived constructor
Inside Derived destructor
Inside Base destructor
在我们的案例中,它被翻译为:
Inside QObject constructor
Inside Parent constructor
Inside Parent destructor
Inside QObject destructor//don't forget that only ~QObject delete children, not a ~Parent
父级的析构函数的执行将在子级析构函数之前开始,并在子级被销毁之后结束。
相关文章:
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- CMake-按正确顺序将项目与C运行时对象文件链接
- 空基优化子对象的地址
- 将对象数组的引用传递给函数
- 你能重载对象变量名本身返回的内容吗
- C++使用整数的压缩数组初始化对象
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 将对象移动到std::shared_ptr
- 代理对象的常量正确性
- 提升 ASIO 无法识别计时器对象
- 将Ref对象作为类成员
- 将包含C样式数组的对象初始化为成员变量(C++)
- 如何返回一个类的两个对象相加的结果
- 使用std::函数映射对象方法
- 是否需要删除包含对象的"pair"?
- 如何在自删除后将对象设置为nullptr
- 迭代时从向量和内存中删除对象
- 构造对象的歧义
- Qt:解构过程中的儿童生活对象