代码一:
<span style="font-size:18px;">#include <iostream>
using namespace std;
int main()
{
const int a = 3;
int* p = const_cast<int*>(&a);
*p = 4;
cout << "value of p: " << *p << endl;
cout << "value of a: " << a << endl;
cout << "address of p: " << p << endl;
cout << "address of a: " << &a << endl;
return 0;
} </span><span style="font-size: 24px;"> </span>
运行结果
value of p: 4
value of a: 3
address of p: 0x22fe34
address of a: 0x22fe34
--------------------------------
Process exited after 0.9921 seconds with return value 0
请按任意键继续. . .
代码二:
#include <iostream>
using namespace std;
const int a = 3;
int main()
{
//const int a = 3;
int* p = const_cast<int*>(&a);
*p = 4;
cout << "value of p: " << *p << endl;
cout << "value of a: " << a << endl;
cout << "address of p: " << p << endl;
cout << "address of a: " << &a << endl;
return 0;
}运行结果:
Segmentation fault (core dumped)
本文通过两个示例展示了如何使用const_cast去除常量限定,并探讨了由此带来的潜在问题。第一个示例成功修改了常量整数的值,而第二个示例则因在全局作用域尝试相同操作而导致段错误。

被折叠的 条评论
为什么被折叠?



