即使通过const_cast更改了const变量,也获得了相同的值 [英] Getting the same value of the const variable even after changing it through const_cast

查看:53
本文介绍了即使通过const_cast更改了const变量,也获得了相同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码段:

int main()
{
    const int i=3;
    int *ptr;

    ptr=const_cast<int*>(&i);
    *ptr=5;

    cout<<"i= "<<i<<endl;  <------------------- statement 1
    cout<<"*ptr= "<<*ptr<<endl;  <------------- statement 2

    return 0;
}

我得到的输出为:

i= 3
*ptr= 5

http://ideone.com/Bvme6

为什么 i 的值没有通过指针更改?

Why is the value of i is not changed through pointer?

我知道抛弃明确声明为const并修改其值的变量的常量性是未定义行为".我很想知道:是否有任何编译器优化机制编译器用值替换程序中的变量"?这意味着语句1被编译器解释为:

I know casting away the const-ness of a variable which is explicitly declared as const and modifying its value is 'Undefined Behavior'. I am curious to know: Is it any compiler optimization mechanism that 'compiler replaces the variable in the program with the value'?. It means the statement 1 is interpreted by the compiler as:

cout<<"i= "<<3<<endl;

即使声明

ptr=const_cast<int*>(&i);    

被替换为

 ptr=(int*)(&i);

我得到的输出相同: http://ideone.com/5lzJA

推荐答案

是编译器用值替换程序中变量的编译器优化机制吗?

Is it any compiler optimization mechanism that compiler replaces the variable in the program with the value?

是;这就是为什么您看不到价值变化的原因.尝试修改 const 对象的行为未定义,以便进行这样的优化(以及将对象放置在不可写的内存中).

Yes; that will be why you don't see the value changing. The behaviour of trying to modify a const object is left undefined in order to allow optimisations like that (as well as allowing the objects to be placed in unwritable memory).

这篇关于即使通过const_cast更改了const变量,也获得了相同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆