常数值可能不一致?

时间:2015-02-15 14:29:10

标签: c++ pointers constants

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

1 个答案:

答案 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