reinterpret_cast는 언제 쓰이나요?
조회수 10982회
언제 reinterpret_cast
를, 언제 static_cast
를 쓰는지 헷갈립니다.
제가 알기로 보통 compile
될 때 type
을 결정하면 static cast
를 쓰는 거라고 알고 있고
reinterpret_cast
는
- integer type을 pointer type로 바꿀 때
- pointer type을 integer type으로 바꿀 때
- pointer type을 다른 type을 가리키도록 할 때
의 경우에 쓰이고, 보통은 쓰지 말아야 할 기능이라고 알고 있습니다
제 코드에서 둘 중 어느 걸 써야 할지 모르겠습니다.
제 코드는 처음엔 C++ object
를 void *
를 이용해서 가리키다
이를 나중에 Class type*
으로 형 변환합니다.
제 경우에는 둘 중 어떤 걸 써야 할까요?
static
으로 compile할 때 cast하는 게 나을까요?
void
에서 Class
로 pointer type
이 바뀌니까 reinterpret_cast
를 써야 할까요?
1 답변
-
질문에 대한 C++ standard는 다음과 같습니다.
static_casting
에서는 pointer가void*
가 되건 다시 원래대로 돌아오건 값이 계속 보존됩니다.(중간 과정에서도 주소 값이 보존) 즉, 다음 예제에서 a, b, c는 같은 주소 값을 저장하고 있습니다.int* a = new int(); void* b = static_cast<void*>(a); int* c = static_cast<int*>(b);
reinterpret_cast
는 pointer를 다른 type으로cast
했다가 또cast
해original type
으로 돌아온 경우,original value
를 보장합니다.(중간 과정에는 주소 값이 어떻게 될지 모름) 즉, 다음 예제에서 a, c는 같은 주소 값을 저장하고 있지만 b는 알 수 없습니다.int* a = new int(); void* b = reinterpret_cast<void*>(a); int* c = reinterpret_cast<int*>(b);
void*
를 casting 하는 경우는,static_cast
가 선호됩니다.
댓글 입력