Consider a class layout :
| A | B | ( class B is derived from A )
0x0 0x8
of course, there is nothing to adjust on downcasting or upcasting. but is behaviour of compiler defined for this case in Standard.?
if not, then, in general, is static_casting of nullptr safe when there is no multiple inheritance.?
A * volatile a_ptr = nullptr ; // or change with B * and cast to A *
assert( ! static_cast< B * >( a_ptr ) ) ; // is that guaranteed by Standard.?
Does compiler always ( in all implementations ) do not perform adjustment.?
and more generally (for case of multiple inheritance), can compiler adjust nullptr within static_cast.?
related question, also unanswered.
static_cast of nullptr is always safe. No matter what is your class layout, you can always static_cast nullptr within class hierarchy and will have defined results - nullptr of the cast type.
Guarantee that any type cast from nullptr will result in nullptr can be found in Standard 5.2.9:
A prvalue of type “pointer to cv1 B,” where B is a class type, can be converted to a prvalue of type “pointerto cv2 D,” where D is a class derived (Clause 10) from B, if a valid standard conversion from “pointer to D” to “pointer to B” exists (4.10), cv2 is the same cv-qualification as, or greater cv-qualification than, cv1, and B is neither a virtual base class of D nor a base class of a virtual base class of D. The null pointer value (4.10) is converted to the null pointer value of the destination type.
Although nullptr can be implictly converted to any pointer type, you might want an explicit cast in some cases, for example, when dealing with templates.
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