Modifying a const through a non-const pointer(通过非常量指针修改常量)
问题描述
我对以下代码中发生的事情感到有些困惑:
I'm a bit confused what happened in the following code:
const int e = 2;
int* w = ( int* ) &e; // (1) cast to remove const-ness
*w = 5; // (2)
cout << *w << endl; // (3) outputs 5
cout << e << endl; // (4) outputs 2
cout << "w = " << w << endl; // (5) w points to the address of e
cout << "&e = " << &e << endl;
在(1)中,w指向e的地址.在(2)中,该值更改为 5.但是,当显示 *w 和 e 的值时,它们的值是不同的.但是如果你打印 w 指针和 &e 的值,它们有相同的值/地址.
In (1), w points to the address of e. In (2), that value was changed to 5. However, when the values of *w and e were displayed, their values are different. But if you print value of w pointer and &e, they have the same value/address.
为什么 e 变成了 5,怎么还包含 2?它们是否存储在单独的位置?还是临时的?但是w指向的值怎么还是e的地址呢?
How come e still contained 2, even if it was changed to 5? Were they stored in a separate location? Or a temporary? But how come the value pointed by w is still the address of e?
推荐答案
正如我在评论中所说,一旦你修改了 const 值,你就处于未定义行为领域,所以谈论什么是没有意义的发生.但到底是什么……
As I said in my comment, once you modified the const value you are in undefined behaviour land, so it doesn't make much sense to talk about what is happening. But what the hell..
cout << *w << endl; // (3) outputs 5
cout << e << endl; // (4) outputs 2
猜测,*w
在运行时被评估,但 e
被视为编译时常量
At a guess, *w
is being evaluated at runtime, but e
is being treated as a compile time constant
这篇关于通过非常量指针修改常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:通过非常量指针修改常量
基础教程推荐
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01