C++ Primer 5th Edition (C++ 11)

top-level-const 可以表示任意的对象是常量, low-level-const 与复合类型 (compound type) 的基本类型 (base type) 部分有关。

As we’ve seen, a pointer is an object that can point to a different object. As a result, we can talk independently about whether a pointer is const and whether the objects to which it can point are const. We use the term top-level const to indicate that the pointer itself is a const. When a pointer can point to a const object, we refer to that const as a low-level const.

涉及描述指针时, top-level-const 表示指针本身是常量, 用 low-level-const 表示指向的对象是一个常量,这个两个名词是作者造出来的,The Draft C++ 11 Standard: N3337 中只有 top-level cv(const and volatile)-qualifier 这个概念。

Examples

想简单的理解这个概念只要把声明读出来就可以了,从右向左。

int i = 0int *const p1 = &i; // p1 is const pointer to int, top-level
const int ci = 42; // ci is const int, top-level
const int *p2 = &ci; // p2 is pointer to const int, low-level
const int *const p3 = p2; // p3 is const pointer to const int, low-level(left) and top-level(right)
const int &r = ci; // r is reference to const int, low-level

low-level-const 在对象拷贝过程中的作用不可忽视。一般来说, 非常量可以转化为常量,反之则不行。

int *p = p3; // invalid, p is pointer to int, p3 is const pointer to const int
p2 = p3; // valid, p2 is pointer to const int, p3 is const pointer to const int
p2 = &i; // valid, pointer to int has been converted into pointer to const int
int &r = ci; // invalid, ci is const int, r needs to be reference to const int instead of reference to int
const int &r2 = i; // valid, r2 is reference to const int, for which it's legal to be bound to int