fab*_*ian 5 c++ language-lawyer c++20
以下代码可以使用 gcc 和 clang 进行编译,但不能使用 msvc。对于 msvc,使用字符串文字初始化 char 数组成员变量似乎会导致根据编译器隐式生成的默认构造函数不是 constexpr:
struct S
{
#if 1
char str[2] = "1";
#else
char str[2] { 'a', '\0'};
#endif
};
int main()
{
constexpr S s; // line 12: compiler error in msvc
constexpr S s2{};
}
Run Code Online (Sandbox Code Playgroud)
MSVC输出
example.cpp
<source>(12): error C2131: expression did not evaluate to a constant
<source>(12): note: failure was caused by call of undefined function or one not declared 'constexpr'
<source>(12): note: see usage of 'S::S'
Compiler returned: 2
Run Code Online (Sandbox Code Playgroud)
参见神箭。
所有编译器都接受对包含对象使用聚合初始化并将数组初始化为字符文字数组。
根据 C++ 20 标准,哪种编译器是正确的?