Language/C++

[C++] 26.Unmanaged Programming: reinterpret_cast

coco_daddy 2024. 1. 30. 15:10
가장 위험한 캐스팅은 reinterpret_cast로, 이 때문에 static_cast가 도입되었다고 해도 과언이 아니다.
// C style

unsigned int myPetAddr = (unsigned int)myPet;
// C++ style

unsigned int myPetAddr = reinterpret_cast<unsigned int>(myPet);
  • reinterpret_cast는 연관 없는 두 포인터 형 사이의 변환을 허용한다.
    • Cat*House*
    • char*int*
  • 또한 포인터와 포인터 아닌 변수 사이의 형 변환을 허용한다.
    • Cat*unsigned int
  • 하지만 주의해야 할 점은 이진수 표기는 달라지지 않는다.
    • int의 이진수를 unsigned int로 해석할 뿐이므로, 부호 등의 정보는 유지되지 않을 수 있다.
int *signedNumber = new int(-10);

unsigned int *unsignedNumber1 = static_cast<unsigned int*>(signedNumber);
// 컴파일 에러

unsigned int *unsignedNumber2 = reinterpret_cast<unsigned int*>(signedNumber);
// 허용 -> 하지만 2의 보수 값이 나타날 것이다.