gpt4 book ai didi

c++ - 在类嵌套静态 const 成员变量初始化 Clang vs GCC 哪个编译器是正确的?

转载 作者:可可西里 更新时间:2023-11-01 16:39:19 27 4
gpt4 key购买 nike

考虑以下代码:

#include <iostream>

struct Foo {
static int const i = i + 1;
};

int main() {
std::cout << Foo::i << std::endl;
}

Clang 版本 3.7 对此进行编译并输出 1

Live Demo

当 GCC 5.3 版发出错误时:

error: 'i' was not declared in this scope

Live Demo

问:

这两个编译器哪个符合C++标准?

最佳答案

GCC 提示名称未声明当然是错误的,因为 i 的声明点是 immediately after its declarator .

但是,可以说 GCC 拒绝整个片段是正确的。 [class.static.data]/3 :

If a non-volatile const static data member is of integral or enumeration type, its declaration in the class definition can specify a brace-or-equal-initializer in which every initializer-clause that is an assignment- expression is a constant expression (5.20).

对于 [expr.const]/(2.7)为了不失败,必须应用其四个子项目符号之一:

an lvalue-to-rvalue conversion (4.1) unless it is applied to

  • a non-volatile glvalue of integral or enumeration type that refers to a complete non-volatile const object with a preceding initialization, initialized with a constant expression, or
  • a non-volatile glvalue that refers to a subobject of a string literal (2.13.5), or
  • a non-volatile glvalue that refers to a non-volatile object defined with constexpr, or that refers to a non-mutable sub-object of such an object, or
  • a non-volatile glvalue of literal type that refers to a non-volatile object whose lifetime began within the evaluation of e;

(2.7.1) 是唯一可能的候选者,但由于 i 之前未使用初始化器初始化,因此它不适用。

请注意,Clang 是 completely consistent :

constexpr int i = i;
void f() {
// constexpr int j = j; // error
static constexpr int h = h;
}

如果 i 具有静态存储持续时间,它似乎会在其初始化程序中将其视为“正确”初始化。我提交了错误 #26858 .

关于c++ - 在类嵌套静态 const 成员变量初始化 Clang vs GCC 哪个编译器是正确的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35792937/

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