执行addressof [英] Implementation of addressof

查看:62
本文介绍了执行addressof的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以前没有意识到 std :: addressof 的存在,为什么存在对我来说很有意义:作为一种在有地址的情况下获取地址的方式 operator& 超载。但是,该实现稍微不透明。从 gcc 4.7.1

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 overloaded operator&. The implementation, however, is slightly more opaque. From gcc 4.7.1:

template<typename _Tp>
inline _Tp*
__addressof(_Tp& __r) _GLIBCXX_NOEXCEPT
{
  return reinterpret_cast<_Tp*>
(&const_cast<char&>(reinterpret_cast<const volatile char&>(__r)));
}

reinterpret_cast< _Tp *> 是显而易见的。其余的都是黑魔法。有人可以弄清楚它的实际工作原理吗?

The reinterpret_cast<_Tp*> is obvious. The rest of it is dark magic. Can someone break down how this actually works?

推荐答案


  • 首先,您拥有 __r 类型为 _Tp&

  • 它是 reinterpret_cast 修改为 char& ,以确保以后能够使用其地址而不必担心 operator& 为原始类型;实际上,它被转换为 const volatile char& ,因为 reinterpret_cast 始终可以合法地添加 const volatile 限定词,即使它们不存在,也不能删除它们(如果存在的话,则确保任何限定词 _Tp 起初是他们,它们不会干扰演员表。)

  • 这是 const_cast '修改为 char& ,删除限定符(现在合法! const_cast 可以执行 reinterpret_cast 不能使用预选赛)。

  • 地址被提取为& (现在我们有一个普通的 char *

  • 这是 reinterpret_cast 的返回 _Tp * (其中包括原始的 const volatile 限定词

    • 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).
    • 编辑:,因为我的答案已被接受,所以我会详尽并添加 char 作为中间类型是由于对齐问题,以避免触发未定义行为。有关完整说明,请参见@JamesKanze的评论(在问题下方)。感谢James如此清晰地解释它。

      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.

      这篇关于执行addressof的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆