在我正在阅读的一本关于 C++ 的书中(C++ for Dummies),有一节内容如下:
int nVar = 10;
int* pVar = &nVar;
const int* pcVar = pVar; // this is legal
int* pVar2 = pcVar; // this is not
书上接着解释:
The assignment pcVar = pVar; is okay -- this is adding the const restriction. The final assignment in the snippet is not allowed since it attempts to remove the const-ness of pcVar
我的问题是为什么最后一行不“合法”。我不明白这如何阻碍 pcVar 的“const-ness”。谢谢。
最佳答案
const int *pcVar = pVar;
int *pVar2 = pcVar;
如果pcVar
是const int *
,这意味着它指向的int
可能是const
。 (在这种情况下不是,但可能是。)因此,如果您分配 pVar2
,这是一个非常量 int *
,它仍然允许 int
指向要修改的。
因此,如果 pcVar
实际上 指向一个 const int
,并且您将一个 int *
分配给它的地址,那么 int *
指针(在本例中为 pVar2
)将允许您通过取消引用来修改它,这是非法的(这是一个约束违规,因此它调用 undefined行为)。
关于C++ 指向常量错误的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15231994/