写程序时发生了内存泄漏:
经过排查,发现是重复delete了verticalSpacer。
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
private:
Ui::Widget *ui;
QSpacerItem* verticalSpacer;
QVBoxLayout* v_layout;
};
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
verticalSpacer = new QSpacerItem(20, 5, QSizePolicy::Minimum, QSizePolicy::Expanding);
v_layout = new QVBoxLayout(this);
v_layout->addItem(verticalSpacer);
}
Widget::~Widget()
{
delete ui;
delete verticalSpacer;
}
在子类中实现,用于添加项。如何添加它对于每个子类来说都是特定的。
Note:item的所有权被转移给layout,删除它是layout的责任。
修改:
Widget::~Widget()
{
delete ui;
}