Search code examples
c++c++11list-initializationaggregate-initialization

Aggregate Initialization when initialization values is fewer than the number of members


As per the document, which states that[emphasise mine]:

Missing initializers in an initializer list

If an aggregate is initialized but the number of initialization values is fewer than the number of members, then all remaining members are initialized with an empty initializer list. In most cases, this will perform value-initialization on those members.

How to understand that in the right way? How remaining members are initialized with an empty initializer list?

The document says this will perform value-initialization on those members in most cases. When is not that case?

Maybe it's easier to understand with a simple example code:

#include <iostream>

struct S {
  int a;
  int b;
};

int main() {
  S s = { 0 }; 
  S s1{ 0 }; 
  //the output will be always zeros?
  std::cout<<"s.a = " <<s.a <<", s.b = " <<s.b<<std::endl;
  std::cout<<"s1.a = "<<s1.a<<", s1.b = "<<s1.b<<std::endl; 
}

Solution

  • How remaining members are initialized with an empty initializer list?

    The same way as A a = {}; (see [dcl.init.aggr] p5.2).

    This member initialization is not equivalent to value-initialization when (and only when) the member is of a class type that does not have a default constructor (which is called if it exists; see [dcl.init.list] p3.5), but has a constructor taking std::initializer_list (which is called otherwise; see [dcl.init.list] p3.7).

    struct A {
        A(std::initializer_list<int>) {}  // #1
    };
    
    A a = {};  // calls #1
    
    struct B {
        int x;
        A a;
    };
    
    B b = {42};  // b.a is initialized by calling #1