顶级或低级常量,或者两者都不存在
Top-level or low-level constness or neither?
我正在学习C++初级读本,如果我理解正确:
- 顶级常量应用于对象本身
- 低级常量意味着被引用对象是常量,这使得被引用对象成为顶级常量
// A plain int.
int i {0};
// Top-level const ints.
const int ci {42};
const int ci2 {0};
// A low-level pointer to const int.
const int * pci {&ci};
// Low-level, because the referenced object can't be changed.
*pci = 0; // error
// But not top-level, because it can be changed to point to another object.
pci = &ci2; // fine
// This is both top-level and low-level const
// because both the pointer and the object it
// points to are const:
const int * const cpci {&ci};
*cpci = 0; // error
cpci = &ci2; // error
现在是问题对于既不是顶级也不是低级的常量,是否有命名约定即指针本身不是常量,但它以常量的方式指向一个非常量对象?或者这是低级惊愕的特殊情况?示例:
int i {0];
int j {42};
// The following pointer is not const itself.
// The object it's pointing to is not const but
// it can't be manipulated through the pointer.
const int * pci {&i};
*pci = 42; // error
// All these are fine:
++i;
pci = &j;
++j;
*pci = 42; // error as above
接受Lightness Races in Orbit的回答后编辑:
我的IDE称它们为只读指针,这对我来说很有意义尽管引用的对象可以通过这种丑陋的强制转换进行更改:
*const_cast<int*>(pci) = 21;
不,不是真的。
您所做的区别是具有const
限定类型的对象和具有const
限定类型的表达式。
因为(从用法的角度来看)哪一个在玩游戏很少重要†,在任何给定的情况下都没有任何有意义的术语来区分它们。
诚然,尽管去掉了const
:,但这确实让解释为什么以下程序是完全有效和定义良好的(如果真的非常糟糕的话)有点麻烦
void foo(const int& x)
{
// the expression `x` has type `const int&` (before decay),
// but after casting away the constness we can modify the
// referent, because it happens to actually be non-`const`.
const_cast<int&>(x) = 66;
}
int main()
{
int x = 42; // object is not const!
foo(x);
}
值得一提的是,尽管"顶级常量"是标准术语,但我对您的"低级常量"不太确定。这些术语甚至不完全对称!Pfft。
†TR
相关文章:
- 当两者都调用时,删除和析构函数之间的区别?
- C++类:virtual和override,或者两者都没有
- 无符号 int 与无符号长 两者都是 32 位,但我无法在不转换的情况下混合它们......为什么?
- 带大小参数和不带大小参数的"运算符删除":当两者都可用时,选择哪一个?
- 将字符串转换为整数。为什么会出现此错误?我想将 ID(字符串)更改为 IC(整数)。两者都是数组。顺便说一句,我仍然是初学者
- 无限循环与无限递归.两者都未定义吗?
- 共享的静音和静音之间的差异(为什么两者都存在于C 17中)
- x&=y 是否等同于 x = x &&y 如果两者都是 c++ 布尔值
- 两种模板类型的sizeof,当两者都是从一个基派生时
- 如果其中一个为真,则 && 结束循环,而不是如果两者都为真
- 如何编写两个初始化操作(一个作为默认初始化,另一个作为用户输入)?两者都是类的构造函数C++
- 要检查它是完整的二叉树还是完全二叉树,或者两者都不是
- 试图使用模数或fmod,但两者都给我的程序带来了问题
- 编译 SkyFireEMU 错误,sizeof(void *) 两者都不是
- 类将自身传递给其他类的构造函数,两者都使用模板定义
- 顶级或低级常量,或者两者都不存在
- 从一个模板类转换到另一个(两者都派生自同一基类)
- 我应该使用virtual, override,还是两者都使用?
- 如何从另一个文件中调用与另一个文件中同名的函数(当两者都包含时)
- 当两者都是普通char类型时,为什么is_base_of会失败?