Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why and when is cast to char volatile& needed?

Tags:

c++

casting

boost

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&?

like image 515
sharptooth Avatar asked Feb 25 '10 12:02

sharptooth


People also ask

Can you cast to volatile?

To access a non-volatile object using volatile semantics, its address must be cast to a pointer-to-volatile and then the access must be made through that pointer.

What is the use of const volatile in c?

The const keyword specifies that the pointer cannot be modified after initialization; the pointer is protected from modification thereafter. The volatile keyword specifies that the value associated with the name that follows can be modified by actions other than those in the user application.

Can pointer be volatile?

Yes, a pointer can be volatile if the variable that it points to can change unexpectedly even though how this might happen is not evident from the code. An example is an object that can be modified by something that is external to the controlling thread and that the compiler should not optimize.


1 Answers

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.

like image 71
Mike Seymour Avatar answered Oct 16 '22 20:10

Mike Seymour