【发布时间】:2023-03-02 21:15:02
【问题描述】:
我确信下面的代码不应该编译。但是,在 g++ 中,它确实可以编译!参见http://codepad.org/MR7Dsvlz 编译。
代码:
#include <iostream>
using namespace std;
int main() {
int x = 32 ;
// note: if x is, instead, a const int, the code still compiles,
// but the output is "32".
const int * ptr1 = & x ;
*((int *)ptr1) = 64 ; // questionable cast
cout << x ; // result: "64"
}
编译这个是g++出错了吗?
【问题讨论】:
-
如果你想抛弃 constness(并且你确定它是允许的),惯用的 c++ 方法是使用
const_cast<int*>(ptr1)- 尽管 C 强制转换也可以,因为你刚刚见过。
标签: c++ pointers casting g++ constants