" a variable that can be easily mistaken for a constant variable but is in fact a non-constant varia

examples of " a variable that can be easily mistaken for a constant variable but is in fact a non-constant variable "

本文关键字:variable is but in non-constant varia constant fact mistaken can that      更新时间:2023-10-16

我是C++新手,正在尝试学习常量表达式的概念。我从入门第 5 版中看到C++下面的引文。

在大型系统中,可能很难确定(确定)初始值设定项是否为常量表达式。我们可以定义一个带有初始值设定项的 const 变量,我们认为这是一个常量表达式。但是,当我们在需要常量表达式的上下文中使用该变量时,我们可能会发现初始值设定项不是常量表达式。

有人可以举一个变量的例子,这个变量很容易被误认为是一个常量变量,但实际上是一个非常量变量?我想了解常数和非常数变量的坑洼,并尽我所能避免它们。

cppreference.com 为该问题提供了一个很好的例子:

// code by http://en.cppreference.com/w/User:Cubbi, CC-by-sa 3.0
#include <iostream>
#include <array>
struct S {
    static const int c;
};
const int d = 10 * S::c; // not a constant expression: S::c has no preceding
                         // initializer, this initialization happens after const
const int S::c = 5;      // constant initialization, guaranteed to happen first
int main()
{
    std::cout << "d = " << d << 'n';
    std::array<int, S::c> a1; // OK: S::c is a constant expression
//  std::array<int, d> a2;    // error: d is not a constant expression
}