在 C++ 中更改 const 变量的值

2022-01-23 00:00:00 constants c++

我正在尝试更改定义为 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.

相关文章