Qt 使用他们所谓的对象树,它与典型的 RAII 方法有点不同。
QObject
类构造函数接受一个指向 parent 的指针QObject
。当该父QObject
级被销毁时,其子级也将被销毁。这是整个 Qt 类中非常普遍的模式,您会注意到很多构造函数都接受*parent
参数。
如果您查看一些 Qt示例程序,您会发现它们实际上在堆上构造了大多数 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
}