为什么常量变量在某个时候不被视为编译时间常量

时间:2016-01-21 09:35:40

标签: c++ c++11 constants stdarray

我尝试执行两种不同的方案:

情景1:

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

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

情景2:

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

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

为什么这两种情况的处理方式不同?

2 个答案:

答案 0 :(得分:3)

因为它可能像

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

此处sz的值在运行时定义。您可以使用constexpr而不是const,而不是在此类初始化时编译错误。

答案 1 :(得分:0)

您可能应该考虑使用constexpr

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