C/C++ 类型转换机制(二)限定符转换

const_cast 只用于处理 const / volatile 属性,只能用于指针和引用。它不能改变底层对象,只是编译器允许你通过一个“非 const”的视角去访问原本标记为 const 的内存。

1. 使用语法

#include <iostream>
using namespace std;


void test()
{
	int value = 100;

	// 只修改指针或引用的 const/volatile 限定符,不会改变类型本身。
	const int* cp = &value;
	int* ip = const_cast<int*>(cp);

	const int& cr = value;
	int& ir = const_cast<int&>(cr);

	// 尝试改变类型报错:E0718: const_cast 只能调节类型限定符;不能更改基础类型
	// char* ip = const_cast<char*>(cp);
}

int main()
{
	test();
	return 0;
}

2. 使用注意

#include <iostream>
using namespace std;


void test01()
{
	const int v1 = 100;
	// 如果原对象本身在定义时就是 const,你用 const_cast 去掉 const 并尝试写入,属于未定义行为
	// 因为编译器可能会把 const 变量放到只读内存段,写入会导致程序直接崩溃
	// 或者编译器做了常量折叠,你虽然改了内存,但读出来的值依然是 10
	int* p1 = const_cast<int*>(&v1);
	*p1 = 200;
	std::cout << v1 << std::endl;

	// 只有当你明确知道底层对象本身不是 const,去掉 const 并修改才是安全的。
	int v2 = 10;
	const int* p2 = &v2;
	int* p3 = const_cast<int*>(p2);
	*p3 = 20;
}

void test02()
{
	int value = 100;
	int& ref = value;
	// 添加 const,一般不用显式使用 cast
	const int& cref1 = ref;

	// 如果非要写,可以写 const_cast 或者 static_cast 都可以,但是通常会选择 static_cast
	const int& cref2 = const_cast<const int&>(ref);
	const int& cref3 = static_cast<const int&>(ref);

	// 原因:去掉 const 会让读者警觉,在动 const,危险。
	// 添加 const 本身是安全的,如果还用 const_cast,会让人第一判断是在去掉 const。
}

class MyClass
{
public:
	// const 版本:负责干实际的活
	const int& get() const
	{
		return data;
	}

	// 非 const 版本:复用 const 版本的逻辑,避免代码重复
	int& get()
	{
		// 把 *this 转成 const 视角,调用 const 版本的 get()
		// 然后把返回值的 const 去掉,安全地返回给外部
		return const_cast<int&>(static_cast<const MyClass&>(*this).get());
	}
private:
	int data;
};

int main()
{
	test01();
	test02();
	return 0;
}