Why does static_cast still work with null pointers despite slicing?

If we use multiple inheritance, slicing will make the addresses for the parent objects different from the address to the sheet objects:

struct X {int x}; struct Y {int y}; struct Z : X, Y {int z}; 

So, if we have an object Z Z , its address &z will not coincide with the address of its parent Y : static_cast<Y*>(&z) is four bytes higher than &z .

The good thing about static_cast is that it is, well, static, so it does not take time to run (compared to dynamic_cast , that is). However, if we have a Z* that points to 0 , each cast to the parent must and should also give a null pointer. Why does it work and how is it implemented? Does this mean that every static_cast introduces a branch instruction?

+4
source share
1 answer

Yes, and the implicit conversion from a pointer to a derived class to a pointer to the base class and static_cast back should save the values โ€‹โ€‹of the null pointer. This means that a branch is usually required in the generated code for multiple inheritance cases where the address of the base class does not match the address of the derived class.

It is theoretically possible for the implementation to reserve a series of addresses around the "null" address to represent null pointers and avoid branching in this case, but this will be due to the addition of an additional check to compare null pointers.

+7
source

All Articles