gpt4 book ai didi

c++ - 没有初始化器的 constexpr 静态数据成员

转载 作者:IT老高 更新时间:2023-10-28 22:39:06 25 4
gpt4 key购买 nike

#include <complex>

struct S
{
static std::complex<double> constexpr c;
};

gcc 生成错误,因为缺少初始化程序。 Clang 和 MSVC 不会产生错误。

据我所知,一个 constexpr 静态数据成员必须有一个初始化器,即使它是具有可以不带参数调用的构造函数的类类型(如本例所示)。不幸的是,我没有最新的 C++ 标准来支持我的假设。

所以正确的代码应该用构造函数初始化,例如:

struct S
{
static std::complex<double> constexpr c {};
};

谁能证明哪个编译器是对的,哪个是错的?

最佳答案

GCC 是错误的。

GCC 对 constexpr 变量使用 C++14 规则,这需要提供初始化程序。这是根据 P0386 更改的。 (粗体字为新增文字):

In 9.2.3.2p3, change:

If a non­-volatile n​on-­inline ​const static data member is of integral or enumeration type, its declaration in the class definition can specify a b​race­-or-­equal-­initializer​ in which every initializer-­clause​ that is an ​assignment-­expression​ is a constant expression (5.20). A​ static data member of literal type can be declared in the class definition with the constexpr specifier; if so, its declaration shall specify a brace­-or-­equal-initializer in which every initializer-­clause that is an assignment­-expression is a constant expression. [ Note: In both these cases, the member may appear in constant expressions. — end note ]​ The member shall still be defined in a namespace scope if it is odr-­used (3.2) in the program and the namespace scope definition shall not contain an initializer.​ A​n inline static data member can be defined in the class definition and may specify a b​race­-or-­equal­-initializer.​ If the member is declared with the constexpr specifier, it may be redeclared in namespace scope with no initializer (this usage is deprecated; see D.X). Declarations of other static data members shall not specify a b​race­-or-­equal-initializer.​

关于c++ - 没有初始化器的 constexpr 静态数据成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50638053/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com