10

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?

GeneralFailure
  • 1,085
  • 3
  • 16
  • 32

1 Answers1

9

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.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480