C ++ Initializer List and Defaults

This code is valid with C ++ 14

using namespace std; struct Point { int x = 0; int y = 0; }; Point p2 {1, 1}; 

It compiles fine with clang ++ 7.0, it does not work with g ++ 4.9 in both cases I pass -std = C ++ 1y to the compiler.

In g ++, it works when I remove the default values โ€‹โ€‹from the structure definition.

 g++ test_constexpr_ctor.cc --std=c++1y -o test test_constexpr_ctor.cc:7:15: error: no matching function for call to 'Point::Point(<brace-enclosed initializer list>)' Point p2 {1, 1}; ^ test_constexpr_ctor.cc:7:15: note: candidates are: test_constexpr_ctor.cc:1:8: note: constexpr Point::Point() struct Point ^ test_constexpr_ctor.cc:1:8: note: candidate expects 0 arguments, 2 provided test_constexpr_ctor.cc:1:8: note: constexpr Point::Point(const Point&) test_constexpr_ctor.cc:1:8: note: candidate expects 1 argument, 2 provided test_constexpr_ctor.cc:1:8: note: constexpr Point::Point(Point&&) test_constexpr_ctor.cc:1:8: note: candidate expects 1 argument, 2 provided 
+6
source share
2 answers

The code is valid.

  • (8.5.4 / 3):

An initialization list of an object or link of type T is defined as follows: - If T is an aggregate, aggregate initialization is performed

  1. An aggregate in C ++ 14 is defined as (8.5.1 / 1):

aggregate is an array or class (clause 9) without constructors provided by the user (12.1), there are no personal or protected non-static data elements (clause 11), there are no base classes (clause 10), and no virtual functions (10.3).

Note that in C ++ 11 this definition looked different (my emphasis):

aggregate is an array or class (clause 9) without constructors provided by the user (12,1), there is no bracket-or-equal-initializer s for non-static data elements (9,2) , there are no private or protected non-static data (section 11), no base classes (clause 10), and no virtual functions (10.3).

Since this part is removed in C ++ 14, your structure is definitely a collection, and therefore aggregate initialization should be performed.

This is fixed in gcc5 (search in the changelog for "aggregates with non-stationary data element initializers"). I would not call this an โ€œerrorโ€, although, rather, the gcc team only implemented this change in gcc 5.1.0.

+3
source

The code you posted is completely correct.

However, you still have a g ++ 4.9.1 version error not yet closed . In fact, this may be a duplicate and closed in some other error report, since the problem is fixed with g++ 5.1.0 or, possibly, even an earlier version. To find the current error, you can use bugzilla search .

+3
source

All Articles