问题
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&
?
回答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