为什么编译器允许你在这里"写"一个const变量?

Art*_*tur 3 c c++ pointers const

为什么你这样欺骗编译器:

const int a = 5;
*((int*)&a)=5;   // VC/armcc does not complain
Run Code Online (Sandbox Code Playgroud)

当上面的"删节"相当于此:

const int *ptr2const = &a;
int *ptr = ptr2const;      // as expected error is raised here
*ptr = 5;
Run Code Online (Sandbox Code Playgroud)

Oli*_*rth 9

Casting是告诉编译器"我知道我在做什么"的方式,所以它不会抱怨.不幸的是,在这种情况下,您将调用未定义的行为.

  • 或者,"不幸的是,在这种情况下,你不知道你在做什么";-) (9认同)

Gre*_*ill 7

C风格的强制转换允许你像你的例子一样抛弃常量.在C++中,您通常会使用新的样式转换,例如static_cast<>,它们不允许您抛弃constness.只const_cast<>允许你这样做.