【发布时间】:2015-12-29 21:28:47
【问题描述】:
我正在处理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 但它以恒定的方式指向非 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
在 Orbit 的回答中接受 Lightness Races 后编辑:
我的 IDE 将它们称为 只读指针,这对我来说很有意义
虽然引用的对象可以用这个丑陋的演员来改变:
*const_cast<int*>(pci) = 21;
【问题讨论】:
-
迁移到 Programmers.SE?
-
直到最近才注意到the standard did not even define top-level cv-qualifier,因此很难找到一个正确的答案。