memory_addressof

memory_addressof (std::addressof)

<memory> 헤더에 정의되어 있어요. operator&가 오버로드되어 있어도 객체나 함수의 실제 주소를 얻어요. C++11부터 도입됐어요.

출처: cppreference

본문

template< class T >
T* addressof( T& arg ) noexcept;   // (1) since C++11, constexpr since C++17

template< class T >
const T* addressof( const T&& ) = delete;   // (2) since C++11
    1. operator&가 오버로드된 경우에도 객체나 함수 arg의 실제 주소를 얻어요.
    1. const rvalue의 주소를 취하는 것을 막기 위해 rvalue 오버로드는 삭제돼요.

표현식 std::addressof(e)e가 lvalue 상수 부분 표현식이면 상수 부분 표현식이에요. (C++17)

매개변수

  • arg: lvalue 객체 또는 함수

반환값

arg에 대한 포인터.

가능한 구현

아래 구현은 reinterpret_cast가 상수 표현식에서 쓸 수 없어서 constexpr이 아니에요. 컴파일러 지원이 필요해요.

template<class T>
typename std::enable_if<std::is_object<T>::value, T*>::type addressof(T& arg) noexcept
{
    return reinterpret_cast<T*>(&const_cast<char&>(
        reinterpret_cast<const volatile char&>(arg)));
}

operator&를 오버로드한 사용자 정의 타입에서도 안전하게 주소를 얻고 싶을 때, 또는 제네릭 코드에서 포인터를 확실히 얻고 싶을 때 std::addressof를 써요. 표준 라이브러리 내부에서도 널리 사용돼요.

더 알아보기 (Learn more)

cppreference