12

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

sharptooth
  • 167,383
  • 100
  • 513
  • 979

2 Answers2

10

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
  • 249,747
  • 28
  • 448
  • 644
4

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
  • 3,460
  • 3
  • 24
  • 31
  • 9
    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 Feb 25 '10 at 13:01
  • 1
    Yup. That aspect of const is indeed confluent with volatile. – Ari Feb 25 '10 at 13:03