我对以下代码中发生的事情感到有些困惑:
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
这篇关于通过非常量指针修改常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
std::reference_wrapper 和简单指针的区别?Difference between std::reference_wrapper and simple pointer?(std::reference_wrapper 和简单指针的区别?)
常量之间的区别.指针和引用?Difference between const. pointer and reference?(常量之间的区别.指针和引用?)
c++ - 如何从指向向量的指针访问向量的内容?How to access the contents of a vector from a pointer to the vector in C++?(c++ - 如何从指向向量的指针访问向量的内容?)
*& 的含义和**&在 C++ 中Meaning of *amp; and **amp; in C++(*amp; 的含义和**amp;在 C++ 中)
为什么我不能对普通变量进行多态?Why can#39;t I do polymorphism with normal variables?(为什么我不能对普通变量进行多态?)
取消引用已删除的指针总是会导致访问冲突?Dereferencing deleted pointers always result in an Access Violation?(取消引用已删除的指针总是会导致访问冲突?)