" 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 "
我是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
}
相关文章:
- C++ Singleton - Prevent ::instance() to variable
- Why is UINT32_MAX + 1 = 0?
- C++错误:"error: int aaa::bbb is protected within this context"
- 创建具有 new in 函数和"this is nullptr"异常的对象
- 使用 cmake 的 Linux 终端上的"Conversion to non-scalar type is requested"错误
- Is !NaN not a NaN?
- Directx 11 - CompileFromFile() is not compiling
- 如何通过多类"Union variable" (sfml) 使用轮询事件
- Centos7 g++ "to_string is not in a member of std"
- "Unable to start debugging. No process is associated with this object." - 在Visual Studio Code中使用GDB
- Where is std::hardware_destructive_interference_size?
- 将成员函数作为构造函数参数调用时出错 "Variable is not a type name"
- 为什么我会收到"Run-Time Check Failure #2 - Stack around the variable 'pr' was corrupted"错误?
- 如何在Visual Studio 2019中修复"[member variable that is a vulkan struct] is uninitialized. Always initiali
- C++ 模板:'Instantiation of variable required here, but no definition is available'
- 分配给数组成员时在 Clang 中"Read-only variable is not assignable"
- " a variable that can be easily mistaken for a constant variable but is in fact a non-constant varia
- 这"if e is a pack, then get a template name, otherwise get a variable name"有效与否?
- 收到警告 C4189 "local variable is initialized but not referenced"即使正在引用变量
- decltype - "the only context in which a variable defined as a reference is not treated as a synonym