Why and when is cast to char volatile& needed?

倾然丶 夕夏残阳落幕 提交于 2019-12-21 07:37:26

问题


In boost::detail::addressof_impl::f() a series of reinterpret_casts is done to obtain the actual address of the object in case class T has overloaded operator&():

template<class T> struct addressof_impl
{
    static inline T* f( T& v, long )
    {
        return reinterpret_cast<T*>(
            &const_cast<char&>(reinterpret_cast<const volatile char&>(v)));
    }
}

What's the purpose of cast to const volatile char& instead of just casting to char&?


回答1:


A cast straight to char& would fail if T has const or volatile qualifiers - reinterpret_cast can't remove these (but can add them), and const_cast can't make arbitrary type changes.




回答2:


The object may be const or volatile, or both (as oxymoronic as that may be), in which case it is probably illegal to reinterpret_cast it to a type that lacks these attributes. (Going in the opposite direction is of course never a problem).



来源:https://stackoverflow.com/questions/2333960/why-and-when-is-cast-to-char-volatile-needed

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