【问题标题】:constexpr function as array sizeconstexpr 函数作为数组大小
【发布时间】:2015-04-16 12:03:17
【问题描述】:

我试图弄清楚为什么我的代码不应该编译:

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

constexpr int ret_one()
{ 
    return 1;
}
constexpr int f(int p) 
{  
  return ret_one() * p; 
}

int main() {
    int i = 2;
    srand(time(0));
    int j = rand();
    int first_array[f(10)];     // OK - 10 is a constant expression
    int second_array[f(j)];     // Error - the parameter is not a constant expression
    j = f(i);                   // OK - doesn't need to be constexpr

    std::cout << sizeof(second_array);
    return 0;
}

所以first_array 定义是可以的。 但是因为j不是常量表达式,所以second_array的定义应该是错误的。在每个程序运行时,我都会得到不同的数组大小。这是它应该如何工作的吗?在我的书中,作者明确指出 constepxr 是一个表达式,其值可以在编译时进行评估。可以在编译时评估 rand() 吗?我认为不可能。

【问题讨论】:

  • 如果您使用 gcc,那么您实际得到的是 VLA

标签: c++ c++11 constexpr


【解决方案1】:

一些编译器,例如 GCC,允许 C 风格的可变长度数组作为 C++ 的扩展。如果您的编译器这样做,那么您的代码将编译。

如果您使用的是 GCC,则可以使用 -Wvla-pedantic 启用警告。

【讨论】:

  • 我用的是 Ideone.com,所以它可能是 GCC。所以据我了解,数组是在运行时分配的,并在块完成时释放。如果 VLA 不可用,C++11 标准将不允许它。对吗?
【解决方案2】:

事实上,

int second_array[f(j)];

将使用非标准 VLA(可变长度数组)扩展。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-13
    • 1970-01-01
    相关资源
    最近更新 更多