the source code: struct C { int a = 2; int b = a + 1; }; C c; //OK constexpr C d; //error int main() { } Why I can't initialize d?
I think it's invalid unless you provide an initializer or the class has a default constructor e.g. constexpr C d = {}; G++ still rejects that though, with a very unhelpful diagnostic: t.cc:8:18: error: ‘constexpr C::C()’ called in a constant expression constexpr C d = {}; //error ^ t.cc:1:8: note: ‘constexpr C::C()’ is not usable as a constexpr function because: struct C ^
Adding an user-defined constexpr C() {} makes it fail more clearly: struct C { int a = 2; int b = a + 1; constexpr C() {} }; test.cc: In constructor ‘constexpr C::C()’: test.cc:6:20: sorry, unimplemented: use of the value of the object being constructed in a constant expression constexpr C() {} and indeed, if `int b = a + 1;` is changed to `int b = 3;`, G++ accepts it.
AFAICS, in mainline this is now an accepts-invalid, because we accept submitter's testcase too as-is. I'm going to add to the testsuite the valid variants in Comments 1 & 2.
Author: paolo Date: Mon Nov 3 10:49:05 2014 New Revision: 217035 URL: https://gcc.gnu.org/viewcvs?rev=217035&root=gcc&view=rev Log: 2014-11-03 Paolo Carlini <paolo.carlini@oracle.com> PR c++/57820 * g++.dg/cpp0x/constexpr-ctor16.C: New. * g++.dg/cpp0x/constexpr-ctor17.C: Likewise. Added: trunk/gcc/testsuite/g++.dg/cpp0x/constexpr-ctor16.C trunk/gcc/testsuite/g++.dg/cpp0x/constexpr-ctor17.C Modified: trunk/gcc/testsuite/ChangeLog
This issue is DR 253, which has not been resolved, but the committee seems inclined to allow this code, so I'm not going to change G++ at this time. http://www.open-std.org/JTC1/SC22/WG21/docs/cwg_toc.html#253
[Adopted at the November, 2016 meeting as part of paper P0490R0.]