Should I delete dynamic element or not in this code?
-
In MainWindow class there is a pointer which is used for creating new window. In that way, should I delete this memory in ~MainWindow() destrcutor? Take and look:
mainwindow.h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include "anotherwindow.h" namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); private slots: void on_pushButtonLogin_clicked(); private: Ui::MainWindow *ui; AnotherWindow *newWindow; }; #endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); } MainWindow::~MainWindow() { delete ui; } // Hide current window and open new window void MainWindow::on_pushButtonLogin_clicked() { hide(); newWindow = new AnotherWindow(); newWindow->show(); }
-
Hi! You don't need to call
delete
on the window: Just give it a parent and then the parent will take care of it. Example code can be found here. -
@Wieland Ok, but what if I can't use this as parent? Should I free it then?
-
@testerius Yes, otherwise you'll leak memory.
-
Direct and right answer which may lead nowhere:
You need to delete every object you allocate with operator new, except if it is QObject subclass and it has a parent. Widgets subclasses may have also delete themselves depending on the flags set when closed.But the problem is not in what to delete, problem is in your design - It does not make sense to create Another window, store the pointer to it in MainWindow then delete MainWindow but try to keep AnotherWindow.
AnotherWindow should be created at least at the same level as MainWindow constructor is called. -
@Oleksandr-Malyushytskyy said in Should I delete dynamic element or not in this code?:
But the problem is not in what to delete, problem is in your design - It does not make sense to create Another window, store the pointer to it in MainWindow then delete MainWindow but try to keep AnotherWindow.
AnotherWindow should be created at least at the same level as MainWindow constructor is called.