数组初始化在 C++ 中使用 const 变量

2022-01-23 00:00:00 arrays constants c++
  1. 这可以工作:

  1. this can work:

const int size = 2;
int array[size] = {0}; 

  • 这有编译错误:

  • this has compile error:

    int a = 2;
    const int size = a;
    int array[size] = {0};
    

  • 为什么?

    推荐答案

    因为 C++ 委员会的人是这么决定的.

    Because the guys in the C++ committee decided so.

    技术原因是用于初始化size的第一个表达式是一个常量表达式,它可以在编译期间计算.这意味着编译器还可以知道数组的大小,并且可以在编译时完成分配(在这种情况下保留"可能是更合适的术语).

    The technical reason is that the first expression that is used to initialize size is a constant expression and it can be computed during compilation. This means that the compiler can also know how big the array is going to be and the allocation (in this case "reservation" may be a more appropriate term) can be done at compile time.

    在第二种情况下,表达式不是常量表达式(给定 C++ 定义),并且这种恢复是不可能的.

    In the second case instead the expression is not a constant expression (given the C++ definition) and this revervation is not possible.

    在第二种情况下,值确实在 size 初始化时固定,这一事实完全无关紧要.规则基于表达式的种类",第二个表达式使用可变变量,因此编译器认为它是非常量的.

    The fact that in the second case the value is indeed fixed by the time size is initialized is totally irrelevant. The rules are base on the "kind of expression" and the second expression uses mutable variables and thus the compiler considers it non-constant.

    允许编译时初始化的第二种形式需要流分析,因为它需要区分

    Allowing the second form for compile-time initialization would require a flow analysis because it would need to distinguish between

    int a = 2;
    const int size = a;
    

    int a = foo();
    const int size = a;
    

    其中涉及 size 的表达式确实是相同的.

    where the expression involving size is indeed identical.

    相关文章