Memory Management
-
Memory Management:
I have little clarification about the memory management.
I have two form with class name as (class first, class second). I placed button in first form to open second form.
mSecond = new second();
mSecond->show();-
Whenever am clicking this button, second form is opening. But every time it creating new object for the second form. how to delete the new object after closing the second form?
-
In first form, how to identify that the second form is closed?
plz suggest the right way to do.
thanks
ram
@
===== main.c =======
#include <QtGui/QApplication>
#include "first.h"int main(int argc, char *argv[])
{
QApplication a(argc, argv);
first mFirst;
mFirst.show();
return a.exec();
}==== first.c========
#include "first.h"
#include "ui_first.h"first::first(QWidget *parent) :
QWidget(parent),
ui(new Ui::first)
{
ui->setupUi(this);
}first::~first()
{
delete ui;
}void first::on_pushButton_clicked()
{mSecond = new second(); mSecond->show();
}
==== first.h =========
#ifndef FIRST_H
#define FIRST_H#include <QWidget>
#include "second.h"namespace Ui {
class first;
}class first : public QWidget
{
Q_OBJECTpublic:
explicit first(QWidget *parent = 0);
~first();private slots:
void on_pushButton_clicked();private:
Ui::first *ui;
second *mSecond;
};#endif // FIRST_H
//===
@ -
-
Please use '@' tags for code.
@
void first::on_pushButton_clicked()
{
if (!mSecond)
mSecond = new second(this);mSecond->show(); }
@Your second is class member, so it's remembered as long as First is valid. No need to call "new" all the time. Also, if you want second to be deleted automatically when First is deleted, add it to QObject hierarchy by assigning the parent (new second(this), or ,Second->setParent(this)).
-
Hi sierdzio,
I tried this but the application crashed
output:
the program has unexpectedly finished.
C:\Qt\KeyMain\debug\KeyMain.exe exited with code -1073741819 -
Add this to your constructor:
@
first::first(QWidget *parent) : QWidget(parent), ui(new Ui::first)
{
ui->setupUi(this);
mSecond = NULL;
}
@If it still fails, debug the bastard. And yes, you still should update your first post with '@' tags.
-
I would say: mSecond uninitialized in constructor (the pointers are not NULL by default)
-
Hi Sierdzio & SGaist,
Thanks for great work. Just assigned "mSecond = NULL;" in constructor it worked perfectly.