Qtはオブジェクトツリーと呼ばれるものを使用しており、通常のRAIIアプローチとは少し異なります。
QObject
クラスコンストラクターは、親へのポインターを取りますQObject
。その親QObject
が破壊されると、その子も破壊されます。*parent
これはQtのクラス全体でかなり一般的なパターンであり、多くのコンストラクターがパラメーターを受け入れることに気付くでしょう。
Qtサンプルプログラムのいくつかを見ると、それらが実際にヒープ上にほとんどのQtオブジェクトを構築し、このオブジェクトツリーを利用して破棄を処理していることがわかります。GUIオブジェクトには固有の存続期間がある可能性があるため、個人的にはこの戦略も役立つと思いました。
Qtは、 (などの)QObject
のサブクラスを使用していない場合、標準のC++以外の追加の保証を提供しません。QObject
QWidget
あなたの特定の例では、何かが削除されるという保証はありません。
次のようなものが必要になります(のサブクラスであると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
}