siv*_*udh 16 c++ qt memory-leaks
我在这里看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"));
}
Run Code Online (Sandbox Code Playgroud)
那些有评论的行
// Memory leak?
Run Code Online (Sandbox Code Playgroud)
不是那些内存泄漏?
如果是这样,既然Window类没有构造函数,那么我应该把所有这些变量(编辑器已经是)Window成员变量?
或者......当Qt超出范围时,内部"删除"那些成员变量?
如果在new和addWidget之间抛出异常,那么是存在内存泄漏.否则,父控件将获得内存的所有权.
QHBoxLayout *buttonLayout = new QHBoxLayout(); // Memory leak?
//make sure you don't throw here
buttonLayout->addWidget(sendButton);
Run Code Online (Sandbox Code Playgroud)
除了Klaim的正确答案:
我会将这些指针存储在a中std::auto_ptr,同时将它们传递给父级.
std::auto_ptr<QHBoxLayout> buttonLayout( new QHBoxLayout() );
// make things which could throw...
layout->addLayout(buttonLayout.release());
Run Code Online (Sandbox Code Playgroud)
这样你肯定不会有泄漏.
从 C++14 开始,您可以使用std::make_unique()便捷的函数模板来创建std::unique_ptr<>具有独占所有权的小部件。然后,在将小部件传递给 时addLayout(),您可以通过调用 使智能指针放弃所有权release():
auto buttonLayout = std::make_unique<QHBoxLayout>();
// ...
// an exception could be thrown here
// ...
layout->addLayout(buttonLayout.release());
Run Code Online (Sandbox Code Playgroud)