Coding Memo

const 포인터 캐스팅 (const_cast) 본문

Language/C++

const 포인터 캐스팅 (const_cast)

minttea25 2024. 5. 2. 15:27
Summary
const로 선언된 포인터는 포인터 값 뿐만 아니라, 해당 포인터가 가리키는 데이터의 변경도 막는다. 따라서 const 변수와 마찬가지로, const 포인터는 const가 아닌 값으로 캐스팅 할 수 없다.

 

const로 선언된 포인터는 해당 포인터가 가리키는 데이터의 변경을 막는다.

 

만약, const 포인터가 가리키는 값을 변경할 필요가 있는 경우, `const_cast`를 사용하여 const 속성을 없애주면 된다.


다음은 예시 코드이다.

using uint = unsigned int;
using ubyte = unsigned char;
uint t = 0xffffffff;
std::cout << t << std::endl;
{
	std::vector<ubyte> someInt(4, 0xFF); // it represents max of unsigned int
	{
		ubyte* ptr = &someInt[0]; 

		auto new_ptr = const_cast<ubyte*>(ptr);
		auto new_ptr2 = reinterpret_cast<uint*>(ptr);
		auto new_ptr3 = reinterpret_cast<uint*>(const_cast<ubyte*>(ptr));

		std::cout << "new_ptr2: " << *new_ptr2 << std::endl;
		std::cout << "new_ptr3: " << *new_ptr3 << std::endl;
	}

	std::cout << '\n';
	{
		const ubyte* const_ptr = &someInt[0];

		auto new_ptr = const_cast<ubyte*>(const_ptr);
		//auto new_ptr2 = reinterpret_cast<uint*>(const_ptr); // compile error!
		auto new_ptr2 = reinterpret_cast<const uint*>(const_ptr);
		auto new_ptr3 = reinterpret_cast<uint*>(const_cast<ubyte*>(const_ptr)); // mutable

		*new_ptr3 = 100; // const 속성이 없으므로 값 변경 가능!

		std::cout << "new_ptr2: " << *new_ptr2 << std::endl;
		std::cout << "new_ptr3: " << *new_ptr3 << std::endl;
	}
}