#include <iostream> int main() { const int a = 10; const int *b = &a; int *c = (int *)b; *c = 10000; std::cout << c << " " << &a << std::endl; std::cout << *c << " " << a << " " << *(&a) << std::endl; return 0; }
输出为:
0037F784 0037F784 10000 10 10
撰写代码的动机是Stroustrup的“C编程语言”中的这句话:
“可以通过显式类型转换显式地删除对const指针的限制”.
解决方法
对于初学者,请参阅Explicit Type Conversion上的这篇文章,特别是:
A pointer to an object of a
const
type can be cast into a pointer to a
non-const
type. The resulting pointer will refer to the original
object. An object of aconst
type or a reference to an object of a
const
type can be cast into a reference to a non-const
type. The
resulting reference will refer to the original object. The result of
attempting to modify that object through such a pointer or reference
will either cause an addressing exception or be the same as if the
original pointer or reference had referred a non-const object. It is
implementation dependent whether the addressing exception occurs.
所以这就解释了为什么它可以让你修改变量而不会bit..
请注意,您可以直接使用转换操作符来实现相同的操作,因为编译器将按照本article on cast operators中的说明为您提供相应的优先顺序.
然而,这里的真正诀窍在于内存模型.一个静态分配的变量,像一个const int a,实际上在内存中实际上不会有任何“物理”位置,并且在编译时就被替换了. (我试图把我的手指在这个实际的参考,但到目前为止,我可以抓住的最接近和最好的是(非常好)SO answer到is memory allocated for a static variable that is never used? – 如果有人找到实际的参考,请让我们知道.)
所以在这里,编译器只是幽默,并试图让你的指针算术尽可能多的感觉,但最终替代了第二次cout调用的最后两个部分的实际值.