Qt:是否“不删除就新建"?导致控件的内存泄漏? [英] Qt: does "new without delete" cause memory leaks with controls?

查看:149
本文介绍了Qt:是否“不删除就新建"?导致控件的内存泄漏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在此处: >

在构造函数中,它们具有:

 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"));
 }

带有注释的行

// Memory leak?

不是那些内存泄漏吗?

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

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

解决方案

否,addWidget()函数将保留该小部件的所有权.然后它将破坏其拥有的小部件.

此外,您还可以在此处阅读:

与QObjects一样,QWidgets可以使用父对象创建,以 指示所有权,确保在没有对象时将其删除 不再使用.使用小部件时,这些父子关系具有 附加含义:每个子窗口小部件都显示在屏幕内 其父窗口小部件占用的区域.也就是说,当您删除 窗口小部件,其中包含的所有子小部件也会被删除.

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?

解决方案

No, the addWidget() function will keep ownership of the widget. It will then destroy the widgets it owns.

Additionally you can read here that:

As with QObjects, QWidgets can be created with parent objects to indicate ownership, ensuring that objects are deleted when they are no longer used. With widgets, these parent-child relationships have an additional meaning: Each child widget is displayed within the screen area occupied by its parent widget. This means that when you delete a window widget, all the child widgets it contains are also deleted.

这篇关于Qt:是否“不删除就新建"?导致控件的内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆