Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default values in C++ initializer lists

I only just learned yesterday that specifying parameters to initializer list items is optional. However, what are the rules for what happens in this case?

In the below example, will ptr be initialized to 0, toggle to false, and Bar default-constructed? I guess this question is sort of redundant, because there would be little point in initializer lists if unspecified argument values == undefined behavior.

Could I also be pointed to the section of the C++ standard that states the behavior in the case of initializer list items not being given arguments?

class Bar
{
    Bar() { }
};

class SomeClass;
class AnotherClass
{
public:
    SomeClass *ptr;
    bool toggle;
    Bar bar;

    AnotherClass() : ptr(), toggle(), bar() { }
    // as opposed to...
    // AnotherClass() : ptr(NULL), toggle(false), bar(Bar()) { }
};
like image 270
Jake Petroules Avatar asked Jan 10 '13 13:01

Jake Petroules


1 Answers

Yes, the members will be initialized to zero and a default-constructed object respectively.

The C++ 11 standard specifies this behavior in 12.6.2/7:

The expression-list or braced-init-list in a mem-initializer is used to initialize the designated subobject (or, in the case of a delegating constructor, the complete class object) according to the initialization rules of 8.5 for direct-initialization.

In turn, 8.5/10 reads:

An object whose initializer is an empty set of parentheses, i.e., (), shall be value-initialized.

Paragraph 8.5/7 defines value-initialized:

To value-initialize an object of type T means:

  • if T is a (possibly cv-qualified) class type (Clause 9) with a user-provided constructor (12.1), then the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);
  • if T is a (possibly cv-qualified) non-union class type without a user-provided constructor, then the object is zero-initialized and, if T’s implicitly-declared default constructor is non-trivial, that constructor is called.
  • if T is an array type, then each element is value-initialized;
  • otherwise, the object is zero-initialized.

And finally, 8.5/5 defines zero-initialized:

To zero-initialize an object or reference of type T means:

  • if T is a scalar type (3.9), the object is set to the value 0 (zero), taken as an integral constant expression, converted to T;
  • if T is a (possibly cv-qualified) non-union class type, each non-static data member and each base-class subobject is zero-initialized and padding is initialized to zero bits;
  • if T is a (possibly cv-qualified) union type, the object’s first non-static named data member is zero- initialized and padding is initialized to zero bits;
  • if T is an array type, each element is zero-initialized;
  • if T is a reference type, no initialization is performed.
like image 101
Jon Avatar answered Sep 25 '22 19:09

Jon