在下面的代码中,p
指针和值都是常量,但b
可以更改*p
的值。这不直观。编译器不应该至少产生警告吗?
int b{3}
const int* const p{&b}
//*p = 5; // correctly produces error
b = 5; // constant value is changed
cout << *p << endl; // shows 5.
答案 0 :(得分:3)
b
未声明为const
,因此您可以随意更改。
仅仅因为您声明了指向const
的{{1}}指针并不意味着const int
本身实际上必须声明为int
。
例如,请考虑此示例。
const
然后
int foo(int const& x) // In the context of this function x is const
{
return x + 5;
}
在上面的示例中,int a = 3; // Note, this is not const
int b = foo(a);
a += 6; // This is fine!
不是a
,而是作为const
传递给函数。因此,只要您不尝试在const&
内修改x
,您就没有做错任何事。但您可以在foo
之外修改a
。