std::addressof - strange implementation

时间:2015-07-28 17:13:29

标签: c++ std

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;
}

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?

1 个答案:

答案 0 :(得分:7)

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.