0

我试图执行两种不同的场景:

场景一:

const auto arraySize = 10; // fine, arraySize is constant 
std::array<int, arraySize> data;

在这里,arraySize 被视为编译时间常数,因此它在 std::array 中是允许的。

场景二:

int sz=10;
const auto arraySize = sz; // fine .
std::array<int, arraySize> data; //error , arraySize is not compile time constant .

在方案 2 中,尽管 arrySize 是 sz 的常量副本,但仍不将 arraySize 视为编译时间常量。

为什么这两种情况被区别对待?

4

2 回答 2

3

因为它可以像

int sz = 0;
std::cin >> sz;
const auto arraySize = sz;

这里的值sz是在运行时定义的。您可以使用constexpr, 而不是const, than 在这种初始化时会出现编译错误。

于 2016-01-21T09:39:51.437 回答
0

您可能应该考虑使用constexpr.

int sz=10;是一个设置为某个常数的变量。编译器可能足够聪明(或不够聪明!)在优化时不断传播它。

于 2016-01-21T09:39:45.467 回答