Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::addressof - strange implementation

Tags:

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?

like image 850
GeneralFailure Avatar asked Jul 28 '15 17:07

GeneralFailure


1 Answers

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.

like image 124
juanchopanza Avatar answered Oct 24 '22 09:10

juanchopanza