changing the value of const variable in C++(在 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 变量的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C++ 中更改 const 变量的值
基础教程推荐
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- C++,'if' 表达式中的变量声明 2021-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- 设计字符串本地化的最佳方法 2022-01-01
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01