Qt使用他们称之为object trees,这是一个有点不同从典型的RAII方法。
QObject
类constructor需要一个父指针QObject
。当父母QObject
遭到破坏时,其子女也将被销毁。这是整个Qt类中相当普遍的模式,您会注意到很多构造函数接受*parent
参数。
如果你看一些Qt example programs,你会发现他们实际上在堆上构建了大多数Qt对象,并利用这个对象树来处理破坏。我个人发现这个策略也很有用,因为GUI对象可能具有特殊的生命周期。
如果您不使用QObject
或QObject
(如QWidget
)的子类,则Qt不会提供超出标准C++的额外保证。
在您的特定示例中,不保证会删除任何内容。
你会想是这样的Des
(假设Des
是QWidget
一个子类):
class Des : public QWidget
{
Q_OBJECT
public:
Des(QWidget* parent)
: QWidget(parent)
{
QPushButton* push = new QPushButton("neu");
QHBoxLayout* layout = new QHBoxLayout(this);
layout->addWidget(push); // this re-parents push so layout
// is the parent of push
setLayout(layout);
}
~Des()
{
// empty, since when Des is destroyed, all its children (in Qt terms)
// will be destroyed as well
}
}
而且你会使用Des
类,像这样:
int someFunction()
{
// on the heap
Des* test = new Des(parent); // where parent is a QWidget*
test->show();
...
// test will be destroyed when its parent is destroyed
// or on the stack
Des foo(0);
foo.show();
...
// foo will fall out of scope and get deleted
}
这似乎工作得很好。谢谢。 但是,当我创建例如4个新的“测试” -widgets并再次关闭它们,创建另一个“测试” -widget不会花费更多的内存,但是应用程序仍然使用尽可能多的内存作为当4“测试” -widgets仍然会存在。这是正常的吗? – Berschi 2009-09-17 14:54:46
@Berschi,Qt或您的操作系统可能会进行一些内存优化。如果你在评论中提到的第五个小部件导致没有更多的内存被使用,我不会担心它太多。如果您担心,另一种选择是找到像valgrind这样的工具并通过它运行您的程序。 – 2009-09-17 22:45:33