创建了一个QLayoutItem指针,并放入一个layout之后,如果在widget析构的时候手动delete QLayoutItem对象会造成程序崩溃,原因如下:
// 步骤1
/*!
\reimp
将item插入layout中时,qt创建了一个struct,然后放入了一个list中
list的定义为:QList<QBoxLayoutItem *> list;
*/
void QBoxLayout::addItem(QLayoutItem *item)
{
Q_D(QBoxLayout);
QBoxLayoutItem *it = new QBoxLayoutItem(item);
d->list.append(it);
invalidate();
}
// 步骤2
/*!
Destroys this box layout.
The layout's widgets aren't destroyed.
layout的析构函数,调用deleteAll函数
*/
QBoxLayout::~QBoxLayout()
{
Q_D(QBoxLayout);
d->deleteAll(); // must do it before QObject deletes children, so can't be in ~QBoxLayoutPrivate
}
// 步骤3
/*
deleteAll函数的定义
就是把list中的对象全部取出来析构掉
*/
inline void deleteAll() { while (!list.isEmpty()) delete list.takeFirst(); }
如果在外部释放了QLayoutItem对象,那qt是不知道的(QLayoutItem没有继承QObject,无法通过QObject的destroyed信号得知对象被释放),会造成了double free,进而程序崩溃。