0%

不同编译器下的差异

在学习C++的时候遇到了一些问题。
在不同编译器下 某些代码无法实现。

在Mac 默认的编译器 clang下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

using namespace std;

struct TestType{
int data;
};

int main(int argc, char *argv[]) {

const TestType x = {20};

TestType *x1 = const_cast<TestType*>(&x);
x1->data = 200;

cout << x.data << endl;
cout << x1->data<< endl;
cout << "Hello world"<< endl;

return 0;
}

编译通过 ,但是运行的时候会出问题。

检查原因,运行到赋值的地方:

1
x1->data = 200;

程序会退出。

但是在msvc等其他编译器下执行则不会出现问题。

其实,我们用const时为了提醒一下自己这个值是个常量,不要动了。但是事实证明 const 常量也是可以改变值的。
但是这就完全没有必要了。