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

查看:20
本文介绍了在 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 的声明以使其像 in 一样 const

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 不会失去常量,而不管它的定义方式如何?

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

推荐答案

这是未定义 const 强制转换的情况之一,因为代码可能已经过优化,因此 w 不是真正的变量,也不真正存在在编译后的代码中.

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天全站免登陆