casting in C++
这是2013年写的一篇旧文,放在gegahost.net上面 http://raison.gegahost.net/?p=39
February 20, 2013
casting in C++
(original work by Peixu Zhu)
Unlike in C language, C++ language offers richer casting features, however, at the same time, it also brings complexity.
Keep in mind that in C++, casting may return a different address rather than the original one !
1. static_cast
- mainly focus on syntax checking at compile time, it can be used to cast a base class into a derived class.
- if it fails, the compiler will give error information.
- in case of casting from a class with multiple parent class, it may return an address offset to the sourcing address. However, casting to void* will not change the address.
2. dynamic_cast
- when it fails, it will return NULL value at run time.
- in case of casting from a class with multiple parent class, it may return an address offset to the sourcing address. However, casting to void* will not change the address.
3. reinterpret_cast
- will not change returned pointers.
- the target must have enough size to accept the source value.
4. casting classes with multiple parent classes
- for force casting/static_cast/dynamic_cast, if the casted class has more than one parent classes, the result may be not the original address, but an address having an offset to the original address. However, though the resulted address is different to the original address, comparative operator will restore the original address temporary, in case of compare to the pointer of original class. That is, the compiler will make both pointer to be the same class type in memory layout.
- However, if the pointer is casted to void*, it will not change the sourcing address.
5. internal of static_cast/dynamic a derived class which has multiple parent classes into a base class:
- get the address of the derived instance.
- if the address is zero, return it.
- if the address is non-zero, compiler will return an address with an offset to the instance address.
6. `==’ operator on two pointers of which one is subobject of another one.
- the compiler check whether the subobject one is non-zero, if it is non-zero, promote it like another one, by changing it’s address temporarily with an offset.
- when the two pointers are compared, compiler will temporary `upgrade’ the subobject to same grade class, then perform the comparison, and if the pointer is NULL, the upgrade is not necessary and then omitted.