What is the purpose of initializing child widgets in the parent window / widget class?

In the VideoWidget and Secure Socket Client examples in Qt, the code presented there activates the child widgets in the parent widgets, for example:

SslClient::SslClient(QWidget *parent)
: QWidget(parent), socket(0), padLock(0), executingDialog(false)

and

VideoPlayer::VideoPlayer(QWidget *parent)
: QWidget(parent)
, mediaPlayer(0, QMediaPlayer::VideoSurface)
, playButton(0)
, positionSlider(0)
, errorLabel(0)

However, further on the code, I see the following:

playButton = new QPushButton;

or in the case of Secure Socket Client, this is:

padLock = new QToolButton;

Why invest in a constructor when it is initialized in code?

+3
source share
3 answers

Why invest in a constructor when it is initialized in code?

Thus, the implementation is safe. Suppose you have this code:

SslClient::SslClient(QWidget *parent)
: QWidget(parent), socket(0), padLock((QToolButton*)(0x0BEEF)), executingDialog(false) {
  throw std::exception();
  padLock = new QToolButton;
}

padLock, , undefined. , nullptr ( free(NULL) C!). , , . , - . , new , . new ( : std::bad_alloc , ).

++, , std::unique_ptr QScopedPointer, . , . RAII . , , ++ , .

++ RAII . , (, Java, #, F #, Python, OCaml Common Lisp), with_resource , . OCaml, Java Python Python . , , ++, , , -, , . ++ RAII.

+3

. , .

. .

, :

QString str;

str . , :

int value;

. , .

, , ... ​​ null .

, , , , Qt, .

0

, ?

I believe that only for the reason that if the actual instance is deferred to another method later, for intance you will not get an uninitialized member in the middle of some operation that causes undefined behavior.

However, in this particular case, this does not make much sense if the code is not changed soon.

It can also come down to coding styles in different projects, but in this special case I don't know that this is limited to the official Qt coding style. For example, in the linux kernel, they prefer not to initialize it like that.

0
source

All Articles