std::addressof - strange implementation

冷暖自知 提交于 2019-12-22 04:05:15

问题


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:


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.



来源:https://stackoverflow.com/questions/31682995/stdaddressof-strange-implementation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!