Implementation of addressof

后端 未结 4 542
遥遥无期
遥遥无期 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:45

    The short version:

    operator& can't be overloaded for char. So the type is being cast to a char reference to get what's guaranteed to be the true address.

    That conversion is done in two casts because of the restrictions on const_cast and reinterpret_cast.

    The longer version:

    It's performing three sequential casts.

    reinterpret_cast
    

    This is effectively casting to a char&. The const and volatile only exist because _Tp may be const or volatile, and reinterpret_cast can add those, but would be unable to remove them.

    const_cast
    

    Now the const and volatile have been removed. const_cast may do that.

    reinterpret_cast<_Tp*> &(result)
    

    Now the address is taken and the type is converted back to a pointer to the original type.

提交回复
热议问题