我尝试创建一个Qt application。使用Valgrind时,我发现有QMenu
引起的内存泄漏。无法确切地弄清楚这一点。我确实尝试遵循QT example for QTMenu class,但即使这样做也会导致泄漏。 Valgrind在addMenu调用中通知泄漏发生在这里:
void MainWindow::createMenu()
{
//Create menus
QAction *quit = new QAction("&Quit", this);
QMenu *file = menuBar()->addMenu("&File");
file->addAction(quit);
connect(quit, &QAction::triggered,
[=]() {
QApplication::quit();
});
//Creating instances of ticker and timer here
//Done so that the connection between ticker and timer is possible
ticker = new Ticker(this);
timer = new Timer(this);
connect(timer, &Timer::timeout, ticker, &Ticker::playSound);
}
这恰好是Valgrind日志
The leaks happen with 78 (32 direct, 46 indirect) bytes in 1 blocks are definitely lost in loss record 11,297 of 16,371
in MainWindow::createMenu() in /home/user/Documents/C/QT/Metronome/MainWindow.cpp:47
1: operator new(unsigned long) in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so
2: 0x1630a434
3: /usr/lib/x86_64-linux-gnu/libQt5Widgets.so.5.5.1
4: QMainWindow::menuBar() const in /usr/lib/x86_64-linux-gnu/libQt5Widgets.so.5.5.1
5: MainWindow::createMenu() in /home/user/Documents/C/QT/Metronome/MainWindow.cpp:47
6: MainWindow::setMainWindow() in /home/user/Documents/C/QT/Metronome/MainWindow.cpp:20
7: MainWindow::MainWindow(QWidget*) in /home/user/Documents/C/QT/Metronome/MainWindow.cpp:6
8: main in /home/user/Documents/C/QT/Metronome/main.cpp:22
所以我的问题是,如何布置菜单以避免内存泄漏?顺便说一句,删除QAction
,QMenu
部分不会导致泄漏。
答案 0 :(得分:-1)
在main()
函数中执行此操作有助于解决此问题:
MainWindow *window = new MainWindow();