简体   繁体   English

指向c ++中的const int的指针

[英]pointer to a const int in c++

While I was learning about const variables in c++, I tried this : 当我在c ++中学习const变量时,我尝试了这个:

#include <iostream>

int main()
{
    const int p = 20;

    int* a = const_cast<int*>(&p);

    *a = 10;

    std::cout<<"Value at a: "<<(*a)<<std::endl;
    std::cout<<"Value of p: "<<p<<std::endl;

    std::cout<<"Their addresses : "<<std::endl;
    std::cout<<a<<" "<<&p<<std::endl;
    return 0;
}

and it produces the output: 它产生输出:

Value at a: 10
Value of p: 20
Their addresses : 
0x7fff4646d7d4 0x7fff4646d7d4

Seemingly I assigned the value 10 to the memory address of p, but their values come out different. 似乎我将值10赋值给p的内存地址,但它们的值不同。 Why is it so? 为什么会这样?

Attempting to modify an object that was originally declared const gives you undefined behaviour. 尝试修改最初声明为const的对象会给您带来未定义的行为。

§7.1.6.1/4 [dcl.type.cv] Except that any class member declared mutable can be modified, any attempt to modify a const object during its lifetime results in undefined behavior. §7.1.6.1/ 4 [dcl.type.cv]除了可以修改任何声明为mutable类成员之外,任何在其生命周期内修改const对象的尝试都会导致未定义的行为。

Chances are, your compiler is replacing all occurences of p in your code with the value 20 , since you have promised that it will not change. 有可能,你的编译器正在用值20替换代码中所有出现的p ,因为你已经承诺它不会改变。 So the line that prints p has changed to: 所以打印p的行已更改为:

std::cout<<"Value of p: "<<20<<std::endl;

So it prints 20 regardless of whether you modified the original object. 因此无论您是否修改了原始对象,它都会打印20 Of course, since you have undefined behaviour, this kind of reasoning is fruitless and you should not invoke undefined behaviour in your program. 当然,由于您有未定义的行为,这种推理是徒劳的,您不应该在程序中调用未定义的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM