通过非常量指针修改常量

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

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

本文标题为:通过非常量指针修改常量

基础教程推荐