在C ++中改变const变量的值 [英] changing the value of const variable in C++

查看:231
本文介绍了在C ++中改变const变量的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图改变一个定义为int const的变量的值,如下所示。

I am trying to change the value of a variable which is defined as int const as below.

const int w = 10;
int* wp = const_cast <int*> (&w);
*wp = 20;

w的值没有改变,即使在赋值后也是10, w和wp都指向相同的存储器位置。但我可以改变w的值,如果定义如下,同时声明

The value of w didn't change and was 10 even after the assignment, though it shows as if both w and wp are pointing to the same memory location. But I am able to the change the value of w, if defined as below while declaring

int i = 10;
const int w = i;

如果我改变i的声明,使它像

If I change the declaration of i to make it const like in

const int i = 10;

w的值不变。

在第一种情况下,w的值如何变化,即使w和wp指向同一个内存位置[这是我打印他们的地址时的印象]

In the first case, how come the value of w didn't change, even though w and wp point to the same memory location [ that was my impression I get when I print their addresses ]

它对编译器有什么区别,它对两种情况的处理方式不同?

What difference it's to the compiler that it treats both the cases differently?

有一种方法可以确保w不会丢失const不考虑它的定义方式?

Is there a way to make sure that w doesn't lose constness, irrespective of the way it is defined?

推荐答案

这是一个const转换未定义的情况,

This is one of the cases where a const cast is undefined, since the code was probably optimized such that w isn't really a variable and does not really exist in the compiled code.

尝试以下方法:

const volatile int w = 10; 
int &wr = const_cast <int &> (w); 
wr = 20; 
std::cout << w << std::endl;

无论如何,我不建议滥用const_cast。

Anyhow, I would not advise abusing const_cast like that.

这篇关于在C ++中改变const变量的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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