c++c++20designated-initializer

Undefined behaviour of Designated initializers in C++


The following C++20 program is accepted without any warning in all compiles I have tried:

struct A { const int & x = z; int y = x; int z; };

int main()
{
    return A{.z=3}.y;
}

https://gcc.godbolt.org/z/nqb95zb7c

But every program returns some arbitrary value. Is it right to assume that this is undefined behavior?


Solution

  • Members are initialized in the order they appear in the class definition, hence the designated initializer is not that relevant, and also this

    struct A { 
        const int & x = z; 
        int y = x;           // <- read of indeterminate value !
        int z = 42;          // <- doesn't really matter because y is initialized before ! 
    };
    
    int main() {
        return A{}.y;
    }
    

    is undefined for the same reason.


    See also the example from cppreference:

    struct A {
      string str;
      int n = 42;
      int m = -1;
    };
    A{.m=21}  // Initializes str with {}, which calls the default constructor
              // then initializes n with = 42
              // then initializes m with = 21
    

    The example is actually to illustrate something else, but it also shows how members are initialized in order.