您的位置:首页 > 运维架构

Top-level const and low-level const

2017-10-06 15:53 429 查看
顶层const:修饰的对象自身(itself)是一个常量,如:

int i = 0;
int* const p = &i;
// p是一个常量,不能改变其值,所以该const是一个顶层const
const int c = 0;
//c同样是一个常量,不能改变其值,所以同样是一个顶层const


底层const:指针或引用所绑定的对象而非自身是一个const:

const int* p1 = &i;
//这里的const不是修饰p1,而是修饰p1所指的对象,是一个const int,
//p1值可变,因而是底层const。
const int& r = i;
//同样是底层const,引用非对象实体,只有底层const


记忆方法:指针或引用相对它们所绑定的对象来说,它们处于更顶层位置,那个对象处于底层,因为可以通过指针或引用来访问底层对象,所以顶层const指的是指针/引用自身是const,底层const指那个对象是const的。

A reference / pointer to const only means that we cannot change the object it refers / points to through the reference / pointer , it says nothing about whether the object to which it refers / points is a const.

int i = 1;
int &r1 = i;
const int &r2 = i;
r2 = 0; // error,cannot change the value of
//i through r2 which refers to a const
r1 = 0; //ok,i can be changed as long as we
//do not use reference to const to
//change the value


Top-level const indicates that an object itself is const, while low-level const ,for example ,when a pointer can point to a const object ,we refer to that const a low-level const.

Top-level const appers in any object type : built-in types , a class type , a pointer type …

Low-level const appers in the base type of compound types : pointers , references …

Kowning that a pointer is an object while a reference is not , so a pointer can have both top-level const and low-level const independently, but a reference can have only low-level const.

const int *const p1= &i; //right-most is a top-level
//const, left-most is a low-
//level
const int &r = i; // low-level const


When we copy an object ,top-level consts are egnored, because top-level const means the object itself is a const , but copying an object does not change the copied object.

On the other hand, when we copy an object ,both objects must have the same low-level const or there is a nonconst to const conversion.

Constexpr imposes a top-level const on the object it defines.

constexpr int *p = nullptr; // p is a const pointer to
//int
const int *q = nullptr; // q is a pointer to const int
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息