从非 constexpression 初始化数组

Array initialization from non-constexpression

我正在尝试理解从 C++ 入门手册中获取的有关数组初始化的示例。 他们说

The number of elements in an array is part of the array’s type. As a result, the dimension must be known at compile time, which means that the dimension must be a constant expression

下面的示例应该会导致错误:

unsigned cnt = 42; // not a constant expression
string bad[cnt];   // error: cnt is not a constant expression

然而,使用 g++ 4.8.4 编译它不会导致错误。

这是书中的错误或过时信息,还是只是 g++ 的一个特性?

是的,它应该是一个 g++ 特性。

当使用-pedantic选项时会发出警告。

测试程序

#include <string>
using std::string;

int main(void){
    unsigned cnt = 42; // not a constant expression
    string bad[cnt];   // error: cnt is not a constant expression
    return 0;
}

结果 Wandbox

prog.cc: In function 'int main()':
prog.cc:6:19: warning: ISO C++ forbids variable length array 'bad' [-Wvla]
     string bad[cnt];   // error: cnt is not a constant expression
                   ^

我觉得这里值得一提的是"alloca"。这就是这些类型的数组的实现方式。当然,它们有自己的局限性,例如不支持运算符的大小。您可以查看详情:http://man7.org/linux/man-pages/man3/alloca.3.html