Home > Back-end >  What's the different between pointer new and default constructor in Qt?
What's the different between pointer new and default constructor in Qt?

Time:05-01

I'm a newer for Qt and C . And I feel about below:

//1
widget a;
a.show();
//2
widget *b=new widget();
b->show();

And I remember widget class (inherited from QWidget) have default constructor. But if I use it in a button like:

void MainWindow::on_pushButton_clicked()
{
    //widget v;
    //v.show();
    widget *v=new widget();
    v->show();
}

The first is shutdown in 10 miliseconds. What cause the difference between them?

Update:

I put this question is because the most popular way to create a windows in qt main is:

#include "mainwindow.h"

#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}

It can work. The .exec() is a endless loop. So I want to know why it can't work in function...

CodePudding user response:

It is because in the first snippet, the object gets placed on the stack, so it will be destructed once it goes out of scope. The new keyword places it on the heap. This means that it will live unil you delete it again, or exit the app. So you have to think about this, because if you don't make sure your object gets deleted, you have a memory leak.

These days there are plenty of smart pointers (also from Qt) out there that will delete your object for you. Qt also will delete children of objects that get deleted, which can also help you manage your memory.

This is a very important bit of c to understand, so you shouldn't try to learn it all from a stackoverflow answer :)


Without knowing your app, i am going to guess that the best option for you here is, is just to add the widget as a member variable of the main window, and just call show() when you need it. This means that it is constructed at the same time as MainWindow.

  • Related