Can you use explicit constructors with designated initializers?

Viewed 105

In the code below, is the initialization of member b legal?

class B {
    public:
        explicit B(int) {}
};

struct A {
    B b;
};

class C {
 public:
    C() : a{.b{33}} {}

    A a;
};

Compiling with the latest version of gcc gives this error (wandbox)

prog.cc: In constructor 'C::C()':
prog.cc:12:11: error: converting to 'B' from initializer list would use explicit constructor 'B::B(int)'
   12 |     C() : a{.b{33}} {}
      |           ^~~~~~~~~

But the latest version of clang compiles the code fine (wandbox)

Which compiler is correct?

1 Answers

This is a gcc bug (submitted 99566).

The rule, from [dcl.init.aggr]/4.2, is:

Otherwise, the element is copy-initialized from the corresponding initializer-clause or is initialized with the brace-or-equal-initializer of the corresponding designated-initializer-clause.

The element (b) should be initialized from the brace-or-equal-initializer ({33}). That's totally fine, that's not copy-initialization. gcc accepts B b{33}, the same kind of thing should happen here.

Related