通过非const指针修改const [英] Modifying a const through a non-const pointer

查看:95
本文介绍了通过非const指针修改const的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点困惑在下面的代码中发生了什么:

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.

如何仍然包含2,即使它更改为5 ?它们是否存储在单独的位置?还是临时的?但是如何让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的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

这篇关于通过非const指针修改const的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆