Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

will destroyed() be emitted if the constructor of a class derived from QObject throws?

Tags:

c++

qt

qobject

Ive seen Qt GUI syntax like the following all over the place:

myDialog::myDialog(QWidget *parent, Qt::WFlags flags):QDialog(parent, flags)
{
    QPushButton *button = new QPushButton("&Download", this);
    QVBoxLayout *layout = new QVBoxLayout(this);
    //something that can throw here
    layout ->addWidget(button );
    setLayout(layout);
}

I've always wondered if this can leak in the event of an exception because the "this" I'm giving as a parent to button and layout is not fully constructed so it might not destroy its children.

I tried it out in MSVC2010 Qt4.8.3 and it looks like as soon as the base QObject class is fully created (which is done first of course) it is ok to pass "this" to other objects in the constructor, they will be destroyed correctly.

I haven't found the spot in the Qt docs guaranteeing this though, can someone point me to it so I have assurance that this will not change in the future?

like image 621
odinthenerd Avatar asked Nov 04 '22 11:11

odinthenerd


1 Answers

I believe it's standard C++ to guarantee that a base constructor is executed prior to derived constructors, though I can't cite chapter and verse from the standard. That said, there is a guarantee that a QObject's destructor will always destroy any children of that QObject.

The Qt convention is that a QObject whose pointer is passed to a QObject or QWidget constructor will become the parent of the newly constructed object. Therefore, when you pass this to button's ctor, button becomes a child of myDialog. Since the QObject portion of myDialog will have already been constructed at that time, I believe you can safely rely on that functionality.

EDIT: I should add that in the example given above, although button starts out as a child of myDialog due to the constructor, it gets reparented when added to layout and becomes a grand-child of myDialog, which should still be deleted by its QObject destructor.

like image 91
Phlucious Avatar answered Nov 12 '22 20:11

Phlucious