指向指针的指针与常量

来源:互联网 发布:北京 职称评审知乎 编辑:程序博客网 时间:2024/06/05 18:04

为了说明这个问题,我们首先给一个错误的例子。

int a = 42;int* b = &a;const int** c = &b; // error

根据const关键词,c所指向的应该是一个常量,不能被改变。如果允许这样转换,则可以通过*c改变指针b的值,由于b不是常量指针,通过b则可以间接改变**c的值,这与常量声明矛盾,例如下面的代码

const int v1 = 10; // this is a constant it should never change int* p1; const int** p2 = &p1; // in reality this is illegal *p2 = &v1; // this is allowed since both "*p2" and "&v1" have type "const int*" *p1 = 11; // now we have modified v1!!! 

C++允许T*转换为const T*,因为这不会产生将常数值改变的问题(上例中的问题)。但是不允许将T**转换为const T**


参考文献:

[1] www.velocityreviews.com/forums/t291343-pointer-to-pointer-to-const.html

[2] www.cplusplus.com/forum/general/12002/

0 0
原创粉丝点击