执行addressof [英] Implementation of 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 achar&
in order to ensure being able to later take its address without fearing an overloadedoperator&
in the original type; actually it is cast toconst volatile char&
becausereinterpret_cast
can always legally addconst
andvolatile
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 justchar&
, removing the qualifiers (legally now!const_cast
can do whatreinterpret_cast
couldn't with respect to the qualifiers). - The address is taken
&
(now we have a plainchar*
) - It is
reinterpret_cast
'ed back to_Tp*
(which includes the originalconst
andvolatile
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屋!