我知道Qt文檔中QLayout
對象是否擁有其小部件的所有權。但就QLayout
對象而言,可以安全地在堆棧上創建它,然後使用setLayout
函數將它傳遞給小部件?還是必須在堆上創建?在堆棧上創建QLayout是否安全?
#include <iostream>
#include <QtGui/QApplication>
#include <QPushButton>
#include <QVBoxLayout>
class LoudPushButton : public QPushButton
{
public:
virtual ~LoudPushButton(){std::cout << "~LoudPushButton()" << std::endl;}
};
class LoudQVBoxLayout : public QVBoxLayout
{
public:
virtual ~LoudQVBoxLayout(){std::cout << "~LoudQVBoxLayout()" << std::endl;}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QWidget window;
// On the heap
LoudQVBoxLayout* mainlayout = new LoudQVBoxLayout;
mainlayout->addWidget(new LoudPushButton);
mainlayout->addWidget(new LoudPushButton);
window.setLayout(mainlayout);
/*
// On the stack
LoudQVBoxLayout mainlayout;
mainlayout.addWidget(new LoudPushButton);
mainlayout.addWidget(new LoudPushButton);
window.setLayout(&mainlayout);
*/
window.show();
return a.exec();
}
兩種選擇//在堆棧和//在堆產生相同的結果在出口處:
~LoudQVBoxLayout()
~LoudPushButton()
~LoudPushButton()
但我可以肯定,這是不是不確定的行爲? window
是否在其佈局上調用delete
?
編輯:
鑑於貓加上另外的答案我想這:
LoudPushButton button;
mainlayout->addWidget(&button);
mainlayout->addWidget(new LoudPushButton);
可生產即使button
和*mainlayout
保證在同一時間被刪除未定義的行爲。這是真的?
我認爲你應該重新考慮接受的答案。我已經編輯了我的帖子,詳細解釋了Cat Plus Plus的答案與Qt的文檔相矛盾。 – cgmb