To start with, I have a struct with one value with a default value
struct S {
int a = 1;
};
This type can be default constructed when it is non-const / non-constexpr by both gcc and clang. Under both, std::is_pod<S>::value
is false
. The weird behavior is as follows:
S s1; // works under both
const S s2{}; // works under both
const S s3; // only works in gcc, clang wants a user-provided constructor
None of the following attempts makes a difference to clang:
struct S {
int a = 1;
constexpr S() = default; // defaulted ctor
virtual void f() { } // virtual function, not an aggregate
private:
int b = 2; // private member, really not an aggregate
};
The only thing I can do that makes this work is to add constexpr S() { }
explicitly. It seems really wrong to me that const S s;
fails while const S s{};
especially when the type is not an aggregate.
The standard makes me think that Clang is right
N4296: 8.5/7
If a program calls for the default initialization of an object of a
const-qualified type T, T shall be a class type with a user-provided
default constructor
So why does gcc allow this, and is S{};
not default initializing, even when the type is not a POD or an aggregate?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…