C++中的顶层const

既然有顶层const,自然就会有底层const。

  • 顶层const:表示指针是一个常量
  • 底层const:表示指向的对象是一个常量

只所以会出现这些定义,是因为在定义指针的时候,const关键字可以瞎几把放。一般来说,定义一个普通变量或引用时:

1
2
3
4
const int a1 = 1;
int const a2 = 2;
const int &r1 = a1;
int const &r2 = a2;

上面代码中,定义的a1、a2都是常量对象,r1、r2都是常量引用。特别的,常量对象a1为顶层const,而常量引用r1为底层const

而在指针上,则不同:

1
2
3
4
5
int a1 = 1;
const int a2 = 2;

const int *p1 = &a2;
int const *p2 = &a1;

如上述代码中,指针p1表示的是指向的对象为const int,该指针无法改变其指向的对象的值,但可以改变其本身的地址值(即可以重新指向其他const int类型的对象);指针p2表示的是指向的对象为int,但指针本身为const的,所以指针无法改变其本身的地址值(即无法重新指向其他对象),但可以看到,由于p2指向的对象为a1,a1为int类型的对象,则a1可以改变自己的值,那么p2的指向的对象的值也会改变。

基于开头所说的定义,可知指针p1是底层const,而指针p2是顶层const

于是就会有奇怪的定义出现:

1
const int *const p = &i;

这种情况下的指针p属于既是顶层const又是底层const

C++中typedef和指针结合时理解 C++的内存分配

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×