More C++ Idioms/Address Of

진영민·2022년 7월 7일
1

More C++ Idioms

목록 보기
1/10

1. 문제 상황

&연산자를 private에 넣어버려 함수 밖에서 reference를 호출하지 못하는 상황

2. 해결 방안

2-1 키워드

reinterpret_cast

reinterpret_cast<new_type>(expression)

임의의 포인터 타입끼리 변환을 허용하는 캐스트 연산자

const_cast

const_cast<new_type>(expression)

포인터 또는 레퍼런스의 const를 잠깐 제거해 주는 용도
volatile을 잠깐 제거해 주기도 함.

volatile

(volatile unsigned int*)

외부적인 요인으로 값이 얼마든지 바뀔 수 있음을 의미

int a;
a = 0;
a = 1;
a = 3;

위의 경우에는 컴파일러가 a=0, a=1을 삭제

volatile int a = 0;
a = 0;
a = 1;
a = 3;

위의 경우에는 변수 대입을 직접 하게 됨.

*하지만 const volatile은 동시에 쓸 수 있음.
함수 내부에서는 바꿀 수 없고 외부에서만 바꿀 수 있음. 읽기 전용

sample code

template <class T>
T* addressof(T& v)
{
    return reinterpret_cast<T*>(&const_cast<char&>(reinterpret_cast<const volatile char&>(v)));
}

해석

reinterpret_cast<const volatile char&>(v)
-->v를 읽기 전용인 char&로 변환

&const_cast<char&>(reinterpret_cast<const volatile char&>(v))
-->읽기 전용 char&를 그냥 char&로 변환

reinterpret_cast<T*>(&const_cast<char&>(reinterpret_cast<const volatile char&>(v)))
-->char&를 다시 원래 자료형으로 변환

해당 변수를 읽기 전용 레퍼런스로 변환 후 읽기 전용을 제거한 뒤 원래 자료형으로 변환하는 방법이다.

reinterpret_cast<T*>(&const_cast<int&>(reinterpret_cast<const volatile int&>(v)));

이러한 방법으로 char대신에 다른 자료형을 사용해도 오류가 나지 않는다.

profile
코린이

0개의 댓글