函数中的 c++ 可变大小堆栈数组获取 const

c++ variable size stack array in function that get const

我正在学习 C++ 我正在阅读 Effective C++(Scott Meyers)一书。 在书中,有一个关于 const 变量的项目,我尝试使用它们。 我注意到一些非常有趣的事情,我知道它是否在 C++ 中有错误: (我正在使用 C++98 标准)

void Test(const int i)
{
    int arr[i] = {0};
    
    for (int j = 0; i > j; ++j)
    {
        arr[j] = i;
    }
}

此函数将完全按照我的意愿编译和工作(在堆栈上创建大小为 'i' 的 int 数组。当我从 'i' 中删除 'const' 时,它不会'编译。 我在 gcc 和 clang 上尝试这个。

编辑: link 到 Compiler Explorer

首先,函数签名中的 const 会被编译器忽略。所以下面两个是等价的:

Test(const int i) {}
Test(int i) {}

其次,无论是否编译,这都不是有效的 C++:

int arr[i] = {0};

无效,因为 i 不是编译时常量,即 i 的值必须在编译时已知。

试穿Compiler Explorer

为了在将来发现这种错误,g++ 和 clang++ 的编译器标志是 -pedantic。永远记得指定你的语言标准,否则你不知道你会得到什么。

$ g++ -std=c++98 -pedantic c++-vla.cpp -o c++-vla
c++-vla.cpp: In function ‘void f(size_t)’:
c++-vla.cpp:3:30: warning: ISO C++ forbids variable length array ‘g’ [-Wvla]
    3 | void f(const size_t x) { int g[x]; }
      |                              ^

$ clang++ -std=c++98 -pedantic c++-vla.cpp -o c++-vla
c++-vla.cpp:3:31: warning: variable length arrays are a C99 feature [-Wvla-extension]
void f(const size_t x) { int g[x]; }
                              ^
1 warning generated.