Qt:是否“新建而不删除"?使用控件导致内存泄漏?

2021-12-31 00:00:00 qt memory-leaks c++

我正在查看 Qt 示例 此处::>

在构造函数中,它们有:

 Window::Window(){编辑器 = 新 QTextEdit();//内存泄漏?QPushButton *sendButton = new QPushButton(tr("&Send message"));//内存泄漏?连接(发送按钮,信号(点击()),这个,插槽(发送消息()));QHBoxLayout *buttonLayout = new QHBoxLayout();//内存泄漏?buttonLayout->addStretch();buttonLayout->addWidget(sendButton);buttonLayout->addStretch();QVBoxLayout *layout = new QVBoxLayout(this);//内存泄漏?布局-> addWidget(编辑器);布局-> addLayout(buttonLayout);setWindowTitle(tr("自定义类型发送"));}

那些带有注释的行

//内存泄漏?

那些不是内存泄漏吗?

如果是这样,既然 Window 类没有构造函数,那么我应该让所有这些变量(编辑器已经是)Window 成员变量?

或者..Qt 是否会在超出范围时在内部删除"这些成员变量?

解决方案

从 C++14 开始,您可以使用 std::make_unique() 方便的函数模板,用于创建 std::unique_ptr<> 拥有小部件的独家所有权.然后,在将小部件传递给 addLayout() 的那一刻,您通过调用 release() 使智能指针放弃所有权:

auto buttonLayout = std::make_unique();//...//这里可能会抛出异常//...布局-> addLayout(buttonLayout.release());

I was looking at Qt example here:

and inside the constructor, they have:

 Window::Window()
 {
     editor = new QTextEdit();   // Memory leak?
     QPushButton *sendButton = new QPushButton(tr("&Send message")); // Memory leak?

     connect(sendButton, SIGNAL(clicked()), this, SLOT(sendMessage()));

     QHBoxLayout *buttonLayout = new QHBoxLayout();  // Memory leak?
     buttonLayout->addStretch();
     buttonLayout->addWidget(sendButton);
     buttonLayout->addStretch();

     QVBoxLayout *layout = new QVBoxLayout(this);    // Memory leak?
     layout->addWidget(editor);
     layout->addLayout(buttonLayout);

     setWindowTitle(tr("Custom Type Sending"));
 }

Those lines with comments

// Memory leak?

aren't those memory leaks?

If so, since the Window class has no constructor, then I should make all of those variables (editor already is) Window member variables ?

Or..does Qt internally "delete" those member variables when it goes out of scope?

解决方案

As of C++14 you can use the std::make_unique() convenience function template for creating an std::unique_ptr<> that has exclusive ownership of the widget. Then, at the moment of passing the widget to addLayout(), you make the smart pointer give up ownership by calling release():

auto buttonLayout = std::make_unique<QHBoxLayout>(); 
// ...
// an exception could be thrown here
// ...
layout->addLayout(buttonLayout.release());

相关文章