顶级或低级常量,或者两者都不存在

Top-level or low-level constness or neither?

本文关键字:或者 两者都 不存在 常量      更新时间:2023-10-16

我正在学习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

相关文章: