简体   繁体   中英

struct initialization with in-class member initializers

I'm having trouble initializing a struct that uses in-class initializers:

struct A
{
    int a{};
    int b{};
};

struct B
{
    int a;
    int b;
};

int main()
{
    A a;    // OK
    B b{1, 2}; // OK
    B b2; // OK, but b.a and b.b are undefined
    A a2{1, 2}; // ERROR!
}

Here's the error I'm getting from gcc 4.7.2:

% g++ -std=c++11 test2.cc
test2.cc: In function ‘int main()’:
test2.cc:16:11: error: no matching function for call to ‘A::A(<brace-enclosed initializer list>)’
test2.cc:16:11: note: candidates are:
test2.cc:1:8: note: constexpr A::A()
test2.cc:1:8: note:   candidate expects 0 arguments, 2 provided
test2.cc:1:8: note: constexpr A::A(const A&)
test2.cc:1:8: note:   candidate expects 1 argument, 2 provided
test2.cc:1:8: note: constexpr A::A(A&&)
test2.cc:1:8: note:   candidate expects 1 argument, 2 provided

Should this work according to the standard, or is this actually illegal? Am I abusing the use of in-class initializers? I thought the new syntax would make it so I wouldn't have to write a constructor just to do this initialization, but now it seems that I may have to resort to that old mechanism to avoid the possibility of an uninitialized structure.

You can only use braces if either

  • the brace content matches a constructor (not your case), or

  • the class is an aggregate and each brace element matches a class member.

However, a class is an aggregate if (C++11, 8.5.1/1):

it has no brace-or-equal-initializers for non-static members

which your class clearly has. So, you don't have an aggregate, either.

Either write suitable constructors, or remove the brace-or-equal-initializers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM