When and How Variables are Initialized? - Part 2 -- Sandor Dargo

SANDOR_DARGO_ROUND.JPGDuring the last two weeks, we saw a bug related to uninitialized values and undefined behaviour, we listed the different kinds of initializations in C++ and we started to more detailed discovery with copy-initialization. This week, we continue this discovery with direct-, list- and aggregate-initialization.

When and How Variables are Initialized? - Part 2

by Sandor Dargo

From the article:

Direct-initialization initializes an object from an explicit set of constructor arguments. Different syntaxes invoke direct initialization such as T object(<at least one arg>);T(<at least one arg>); or new T(<at least one arg>); but it might also happen when you use curly braces (T object{oneArg};). Additional use cases are static casts, constructor initializer lists and values taken by value in lambda captures.

While at first glance this might obvious there are some catches.

Take this expression: T object{ arg };. In this case, object is directly initialized only if it’s a non-class type, otherwise, we talk about list-initialization. But if you use the parentheses syntax (T object(arg) then there is no such distinction between class and non-class types, in both cases, direct-initialization is performed. Also, T object{ arg1, arg2 }; would never be direct-initialized, that’s always an aggregate-initialization.

In the expression [arg]() {}, the generated lambda members will not be copy-initialized, but they will be directly initialized.

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.