const_cast是C++中的一种类型转换操作符,用于去除变量的const限定符,使其变为非const类型。他的基本语法如下
const_cast<type>(expression)
其中type表示目标类型,expression表示要转换的表示,const_cast返回指向目标类型的指针或者引用。
需要注意的是,const_cast 只能用于去除变量的 const 限定符,如果在运行时修改了被转换变量的值,那么行为是未定义的。因此,在使用 const_cast 时需要特别小心,确保不会导致未定义行为。
例如,下面的代码演示了如何使用 const_cast 去除变量的 const 限定符:
#include <iostream>
using namespace std;
int main() {
const int num = 10; // const variable
int &ref_num = const_cast<int&>(num); // cast away const
ref_num = 20; // undefined behavior cout << num << endl; // may print 10 or 20 or something else return 0;
}
在上面的代码中,定义了一个 const 类型的变量 num,然后使用 const_cast 将其转换为非 const 引用类型,最后修改了该变量的值。由于 num 是一个 const 变量,其值不应该被修改,因此该代码存在未定义行为,输出的结果也是不确定的。