【发布时间】: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。