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++ 迭代器有什么问题? 2022-01-01
- CString 到 char* 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 初始化列表*参数*评估顺序 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
