본문 바로가기
프로그래밍 언어/C,C++

C++ const_cast, static_cast, reinterpret_cast

by pagehit 2021. 8. 18.
반응형

named conversion을 이용해 하나의 타입에서 다른 타입으로 명시적으로 형변환을 할 수 있다. 보통 implicit conversion을 사용하지 못할 때 쓴다. 대개 아래와 같은 형식을 취한다.

 

named-conversion<desired-type>(object-to-cast)

 

const_cast

const 변수를 받아 const를 벗겨준다.(cast away)

 

void carbon_thaw(const int& encased_solo) {
  //encased_solo++; // Compiler error; modifying const
  auto& hibernation_sick_solo = const_cast<int&>(encased_solo);
  hibernation_sick_solo++;
}

 

const_cast를 이용해 volatile modifier를 제거할 수도 있다.

 

static_cast

잘 정의된 implicit conversion을 역으로 수행한다. 예를 들어 short*에서 void*는 잘 정의된 implicit conversion이다. 이 반대의 과정을 static_cast로 할 수 있다. implicit cast를 다시 되돌리기 위해 static_cast를 사용한다.

네트워크 프로그래밍이나 바이너리 파일을 처리할 때 raw byte를 해석하기 위해 사용한다.

char*를 float*로 변환하는 것은 컴파일 에러가 난다. 이런 상황에서 staic_cast<char *>()는 에러를 발생시키므로 reinterpret_cast를 사용한다.

#include <cstdio>
short increment_as_short(void* target) {
  auto as_short = static_cast<short*>(target);
  *as_short = *as_short + 1;
  return *as_short;
}

int main() {
  short beast{ 665 };
  auto mark_of_the_beast = increment_as_short(&beast);
  printf("%d is the mark_of_the_beast.", mark_of_the_beast);
}

// 666 is the mark_of_the_beast.

 

reinterpret_cast

잘 정의되지 않은 conversion에서 수행한다. 시스템 프로그래밍이나 임베디드에서 메모리를 직접 해석할 필요가 있을 때 사용한다. 그만큼 책임이 따른다.

 

#include <cstdio>
int main() {
  auto timer = reinterpret_cast<const unsigned long*>(0x1000);
  printf("Timer is %lu.", *timer);
}

// 메모리 주소 0x1000을 unsigned long으로 해석

 

위는 메모리 주소 0x1000을 unsigned long 변수로 해석한다. 

 

반응형

댓글