tags:

views:

83

answers:

2

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

+3  A: 

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).

Ari
It's not oxymoronic to be both `const` and `volatile`. For example, a read-only hardware register that gives a different value each time it's read, or a read-only object in shared memory that's updated by another process, should have both qualifiers.
Mike Seymour
Yup. That aspect of const is indeed confluent with volatile.
Ari
+3  A: 

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.

Mike Seymour