本文介绍了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()
函数将保留该小部件的所有权.然后它将破坏其拥有的小部件.
此外,您还可以在此处阅读:
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:
这篇关于Qt:是否“不删除就新建"?导致控件的内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!