Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using "this" in contructor's initialization list specificly dangerous with Qt?

I need reliable information about "this" subject:

class MyClass, public QWidget
{
public:
    MyClass( QWidget * parent = NULL )
         :QWidget( parent ),
         mpAnotherWidget( new QWidget( this ) ){};
private:
    QWidget * mpAnotherWidget;
};

Of course, calling virtual functions in contructor OR initialization list is a bad idea. The Question is: can this code

mpAnotherWidget( new QWidget( this ) )

lead to undefined behavior?! And if so: why ?

Please quote your sources if you can! Thanks!

like image 796
LalaBox Avatar asked Apr 01 '15 11:04

LalaBox


People also ask

Is it safe to use this in constructor?

Some people feel you should not use the this pointer in a constructor because the object is not fully formed yet. However you can use this in the constructor (in the {body} and even in the initialization list) if you are careful.

What is a constructor initializer list and what are its uses?

Constructor is a special non-static member function of a class that is used to initialize objects of its class type. In the definition of a constructor of a class, member initializer list specifies the initializers for direct and virtual bases and non-static data members.

What is the use of initialization list in C++?

When do we use Initializer List in C++? Initializer List is used in initializing the data members of a class. The list of members to be initialized is indicated with constructor as a comma-separated list followed by a colon. Following is an example that uses the initializer list to initialize x and y of Point class.

What is std :: Initializer_list?

An object of type std::initializer_list<T> is a lightweight proxy object that provides access to an array of objects of type const T .


1 Answers

It depends on what QWidget does with the pointer it is given. It is perfectly fine to pass around a reference or pointer to a half-constructed object as long as the called code does not access the underlying object. You need to look into the documentation of QWidget to know whether it touches the object or just stores the pointer.


In the particular case of Qt, reading the documentation, it is calling the constructor of QWidget, the argument is of type QWidget*, and this is only used to cast to the base pointer. Obtaining the pointer to the base is guaranteed in 12.7/3 as the requirement for the conversion is that the construction of X and the construction of all of its direct or indirect bases that directly or indirectly derive from B shall have started. The pointer is then passed to the QWidget constructor that may use it in any way it wants, since the constructor for the base QWidget has already completed before the constructor for the mpAnotherWidget starts.

like image 96
David Rodríguez - dribeas Avatar answered Sep 28 '22 04:09

David Rodríguez - dribeas