std::addressof - 奇怪的实现 [英] std::addressof - strange implementation
问题描述
所以几天前我了解了 std::addressof.在 http://en.cppreference.com/w/cpp/memory/addressof 一个可能的实现是给定:
So a few days ago i learned about std::addressof. At http://en.cppreference.com/w/cpp/memory/addressof a possible implementation is given:
template< class T >
T* addressof(T& arg)
{
return reinterpret_cast<T*>(
&const_cast<char&>(
reinterpret_cast<const volatile char&>(arg)));
}
据我所知,这可以简单地实现如下:
As far i see this can simply be implemented like:
template<typename T>
T* addressof( T& var )
{
return &var;
}
为什么 cppreference 的人选择用 3 个强制转换来实现它?是否有任何我遗漏的细节使他们的实施更好.当您所做的只是强制转换时,使用 volatile 有什么意义?
Why the guys at cppreference chose to implement it with 3 casts? Is there any detail I am missing that is making their implementation better. What is the point in using volatile when all you do is cast?
推荐答案
如果它可以像你的例子那样实现,就没有必要了.关键是它为您提供了对象的地址,即使该类型的 operator&
的地址已被重载.
If it could be implemented like in your example, there would be no need for it. The point is that it gives you the address of an object, even if the address-of operator&
for that type has been overloaded.
这篇关于std::addressof - 奇怪的实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!