c++ - 在堆栈上创建 QLayout 是否安全?

标签 c++ qt

我从 Qt 文档中知道 QLayout 对象拥有其小部件的所有权。但就 QLayout 对象而言,在堆栈上创建它然后使用 setLayout 函数将其传递给小部件是否安全?还是必须在堆上创建?

#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

编辑:

鉴于Cat Plus Plus的回答我猜想:

LoudPushButton button;
mainlayout->addWidget(&button);
mainlayout->addWidget(new LoudPushButton);

即使 button*mainlayout 保证同时被删除,也会产生未定义的行为。这是真的吗?

最佳答案

每个 QObject 都会删除它的子对象。只有没有父对象的对象才能有自动存储。 QWidget::setLayout 重新设置布局的父级。所以,不,你不能用 QLayout 做到这一点。

关于c++ - 在堆栈上创建 QLayout 是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10399304/

相关文章:

c++ - 检查对象类型真的总是糟糕设计的标志吗?

c++ - 使用类包装器对对象进行线程安全访问是否符合 C++11?

c++ - CreateInstance 例程的模板函数

c++ - 具有 Qt 信号/槽的生产者/消费者

c++ - QPainter怎么转? (从工厂函数中 move 一个对象)

c++ - 如何使用自定义消息扩展 Inet 的不同模块?

c++ - 在不使用Abs函数或if语句的情况下获取绝对值

python - Qt:曲线编辑器或类似的东西?

c++ - 带有确定和取消按钮的 QDialog

visual-studio - LNK1112 模块机器类型 'X86' 与目标机器类型 'x64' 冲突