Critique each of the following C ++ casts for style and correctness.
First, a general note: All of the followingDynamic_castS wocould be errors if the classes involved did not have virtual functions. Fortunately,ADoes provide a virtual function, making allDynamic_castS legal.
void g() { unsigned char* puc = static_cast<unsigned char*>(&c); signed char* psc = static_cast<signed char*>(&c);
Error: we must useReinterpret_castFor both cases. This might surprise you at first, but the reason is thatChar,Signed Char, AndUnsigned charAre three distinct types. Even though there are implicit conversions between them, they are unrelated, so pointers to them are unrelated.
void* pv = static_cast<void*> (&b1); B* pb1 = static_cast<B*>(pv);
These are both fine, but the first is unnecessary, because there is already an implicit conversion from a data pointer toVoid *.
B* pb2 = static_cast<B*> (&b1);
This is fine, but unnecessary, since the argument is alreadyB *.
A* pa1 = const_cast<A*>(&ra1);
This is legal, but casting awayConst(OrVolatile) Is usually indicative of poor style. Most of the cases in which you legitimately wowould want to removeConst-Ness of a pointer or reference are related to class members and covered byMutableKeyword. See item 43 for further discussionConst-Correctness.
Guideline
|
Avoid casting awayConst. UseMutableInstead. |
A* pa2 = const_cast<A*>(&ra2);
Error: this will produce undefined behavior if the pointer is used to write on the object, becauseA2Really isConstObject. To see why this is a legitimate problem, consider that a compiler is allowed to see thatA2Is created asConstObject and use that information to store it in read-only memory as an optimization. casting awayConstOn such an object is obviously dangerous.
Guideline
B* pb3 = dynamic_cast<B*>(&c1);
Potential error (if you try to usePB3): BecauseC1IS-NOT-AB(BecauseCIs not publicly derived fromBLimit n fact, it is not derived fromBAt all), this will setPB3To null. The only legal cast wocould beReinterpret_cast, And using that is almost always edevil.
A* pa3 = dynamic_cast<A*>(&b1);
Probable error: BecauseB1Is-not-A(BecauseBIs not publicly derived fromA; Its derivation is private), this is illegal unlessG ()Is a friendB.
B* pb4 = static_cast<B*>(&d1);
This is fine, but unnecessary because derived-to-public-base pointer conversions can be done implicitly.
D* pd = static_cast<D*>(pb4);
This is fine, which may surprise you if you expected this to requireDynamic_cast. The reason is that downcasts can be static when the target is known, but beware: You are telling the compiler that you know for a fact that what is being pointed to really is of that type. if you are wrong, then the cast cannot inform you of the problem (as cocouldDynamic_cast, Which wocould return a null pointer if the cast failed) and, at best, you will get spurious run-time errors and/or program crashes.
Guideline
pa1 = dynamic_cast<A*>(pb2); pa1 = dynamic_cast<A*>(pb4);
These two look very similar. Both attempt to useDynamic_castTo convertB *IntoA *. However, the first is an error, while the second is not.
Here's the reason: As noted above, you cannot useDynamic_castTo cast a pointer to what really isBObject (and herePBSPoints to the objectB1) IntoAObject, becauseBInherits privately, not publicly, fromA. However, the second cast succeeds becausePb4Points to the objectD1, AndDDoes haveAAs an indirect public base class (throughC), AndDynamic_castIs able to cast against ss the inheritance hierarchy using the pathB * D * C * A *.
C* pc1 = dynamic_cast<C*>(pb4);
This, too, is fine for the same reason as the last:Dynamic_castCan navigate the inheritance hierarchy and perform cross-casts, so this is legal and will succeed.
C& rc1 = dynamic_cast<C&>(*pb2); }
Finally, an "exceptional" error: Because* PBSIsn' t reallyC,Dynamic_castWill throwBad_castException to signal failure. Why? Well,Dynamic_castCan and does return NULL if a pointer cast fails, but since there's no such thing as a null reference, it can't return a null reference if a reference cast fails. there's no way to signal such a failure to the client code besides throwing an exception, so that's what the standardBad_castException class is.