Implementation of addressof

后端 未结 4 566
遥遥无期
遥遥无期 2020-12-24 06:24

Having previously been unaware of the existence of std::addressof, why it exists makes sense to me: as a way of taking the an address in the presence of an over

4条回答
  •  死守一世寂寞
    2020-12-24 06:42

    • First you have __r which is of type _Tp&
    • It is reinterpret_cast'ed to a char& in order to ensure being able to later take its address without fearing an overloaded operator& in the original type; actually it is cast to const volatile char& because reinterpret_cast can always legally add const and volatile qualifiers even if they are not present, but it can't remove them if they are present (this ensures that whatever qualifiers _Tp had originally, they don't interfere with the cast).
    • This is const_cast'ed to just char&, removing the qualifiers (legally now! const_cast can do what reinterpret_cast couldn't with respect to the qualifiers).
    • The address is taken & (now we have a plain char*)
    • It is reinterpret_cast'ed back to _Tp* (which includes the original const and volatile qualifiers if any).

    Edit: since my answer has been accepted, I'll be thorough and add that the choice of char as an intermediate type is due to alignment issues in order to avoid triggering Undefined Behaviour. See @JamesKanze's comments (under the question) for a full explanation. Thanks James for explaining it so clearly.

提交回复
热议问题