我正在处理 C++ Primer如果我理解正确的话:
- 顶级常量适用于对象本身。
- 低级常量意味着被引用对象是常量,这使得被引用对象成为顶级常量。
// 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
现在是问题。 对于既不是顶级也不是低级的常量是否有命名约定?即指针本身不是 const 但它以常量方式指向非常量对象?或者这是低级常量的特例?示例:
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;
最佳答案
不,不是真的。
您要区分的是 object 与 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);
}
尽管"top-level const" is standard terminology 物有所值,我不太确定你的“低级常量”。这些术语甚至不完全对称!噗。
† 在 foo()
上面我们实际上不会写const_cast
因为我们假设所有输入都是对对象的引用,这些对象实际上是 const
.
关于c++ - 顶级或低级常量或两者都不是?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34519369/