核心常量表达式和数组索引

Core constant expression and array indexing

参考以下代码段:

Core constant expressions

int main() {
    const std::size_t tabsize = 50;
    int tab[tabsize]; // OK: tabsize is a constant expression

    std::size_t n = 50;
    const std::size_t sz = n;
    int tab2[sz]; // error: sz is not a constant expression
                  // because sz is not initialized with a constant expression
}

当我使用 (gcc 4.2) 编译上面的代码段时:

g++ -ggdb -pedantic -std=c++14 -Wall

对于代码中突出显示为错误的行,仅生成以下警告:

 warning: variable length arrays are a C99 feature
      [-Wvla-extension]
    int tab2[sz]; // error: sz is not a constant expression
            ^

这似乎与上述 link 中概述的要求相矛盾,即核心常量表达式不得计算左值->右值隐式转换,除非值:

has integral or enumeration type and refers to a complete non-volatile const object, which is initialized with a constant expression

感谢您的想法。

支持可变长度数组是一种编译器扩展,标准通常允许这种扩展,只要它不会使一致的代码表现不同,并且只要它们它是一个扩展(GCC 对该警告进行了处理):

A conforming implementation may have extensions (including additional library functions), provided they do not alter the behavior of any well-formed program. Implementations are required to diagnose programs that use such extensions that are ill-formed according to this document. Having done so, however, they can compile and execute such programs.

[intro.compliance]/8

如果需要,您可以通过 -pedantic-errors 禁用所有扩展。