In boost::detail::addressof_impl::f() a series of reinterpret_cast
s 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&
?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With