const_cast <double*>有效,但const_cast <int*>不起作用

Tom*_*ker 1 c++ pointers integer const-cast

我的问题是,为什么第一部分代码在第二部分工作时不起作用.非const指针应该先使用const_cast修改const值,但是使用整数这个技巧不起作用.你能解释一下为什么会这样吗?

const int i = 5;
cout << i << endl; //output: 5
int *ptr_i = const_cast<int*>(&i);
*ptr_i = 100;
cout << i << endl; //output : 5

const double d = 5;
cout << d << endl; //output : 5
double *ptr_d = const_cast<double*>(&d);
*ptr_d = 100.; 
cout << d << endl; //output : 100
Run Code Online (Sandbox Code Playgroud)

Tar*_*ama 5

修改const变量是未定义的行为:

n4296§7.1.6.1/ 4

除了可以修改声明为mutable(7.1.1)的任何类成员之外,任何在其生命周期内修改const对象的尝试(3.8)都会导致未定义的行为.

const_cast通常用于与非const-correct API通信或丢弃volatile限定符; 它不应该像这样使用.