常数值可能不一致?

possible inconsistency in constant values?

在下面的代码中,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. 

b 未声明 [​​=13=] 因此您可以随意更改它。

仅仅因为您声明了指向 const intconst 指针并不意味着 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& 传递给函数的。因此,只要您不尝试在 foo 内修改 x,您就没有做错任何事情。但是您可以在 foo.

之外修改 a