Gotcha #41: Static Casts
By "static casts" we mean—unsurprisingly—non-dynamic casts. Under this definition, we include not only the static_cast operator but also reinterpret_cast, const_cast, and old-style casts.
The basic problem with static casts is that they're static. In employing such a construct, we're asking the compiler to accept our version of an object's capabilities rather than the object's version. While many uses of static casts may result in code that is initially correct, that code is not able to adjust itself automatically to future changes in an object's type structure. Because these changes are generally remote from the point of the cast, maintainers often do not modify the code containing the cast. At the same time, the cast has the additional effect of turning off any diagnostics the compiler would otherwise have provided.
Casts are not essentially evil, but they must be used in moderation and in such a way that maintenance of code remote from the cast will not invalidate the cast. From a practical perspective, these requirements imply that one should, in general, avoid casting abstract data types and, most particularly, abstract data types in a hierarchy.
Consider a simple hierarchy:
class B {
public:
virtual ~B();
virtual void op1() = 0;
};
class D1 : public B {
public:
void op1();
void op2();
virtual int thisop();
};
Associated with the hierarchy is a function that serves as a factory to create some sort of B object. Initially, we may have only a single derived class, so its implementation is trivial:
B *getAB() { return new D1; }
Unfortunately, the original developer or a maintainer may require access to the D1-specific functionality of the object returned from getAB. The proper procedure in this case is to redesign so that the type of the object is known statically. If that isn't possible or practical, a dynamic_cast may be used (after appropriate soul-searching). It's almost never a good idea to use a static cast, as we have here:
B *bp = getAB();
D1 *d1p = static_cast<D1 *>(bp);
d1p->op1();
d1p->op2();
int a = d1p->thisop();
This code works only because the returned object is actually a D1. This simple situation is not likely to last, and a new derived class will be added to the hierarchy along with an updated factory:
class D2 : public B {
public:
void op1();
void op2();
virtual char thatop();
};
// . . .
B *getAB() {
if( rand() & 1 )
return new D1;
else
return new D2;
}
Note that these changes probably take place in a remote part of the code not frequented by the maintainer of code containing the static cast. One would hope that the modification of the getAB function would at least provoke a recompilation of this code, but even that is not guaranteed. Even if the code is recompiled, the use of a static cast ensures that the compiler will issue no diagnostic. Few guarantees can be made about the behavior of this code when getAB returns an object of type D2, but it's quite possible it could actually run, after a fashion. The comments below indicate commonly observed behavior:
B *bp = getAB(); // gets a D2
D1 *d1p = static_cast<D1 *>(bp); // pretend D2 is a D1
d1p->op1(); // #1: call D2::op1!
d1p->op2(); // #2: call D1::op2!!
int a = d1p->thisop(); // #3: call D2::thatop!!!
In spite of the lack of a guarantee of this behavior, the line marked #1 is probably going to do "the right thing." Of course, it would have been preferable if the function op1 were invoked through the base class interface, because this would guarantee correct behavior.
The line marked #2 is more problematic. It's a nonvirtual member function call to a member of D1. Unfortunately it's being passed a D2 object, which will result in undefined runtime behavior. It may even work.
The line marked #3 is perhaps the most problematic. Statically, we invoke a virtual function of D1 named thisop that returns an int. Dynamically, we invoke a virtual function of D2 named thatop that returns a char. If this code manages to run without aborting, we'll attempt to copy a char result into an int.
Use of a static cast is often, as Scott Meyers has observed, "a sign that negotiations between you and your compiler have broken down." In effect, a static cast not only tells your compiler "Because I say so" (and, as with a similar discussion with a human interlocutor, guarantees the end of any useful communication); it shows a lack of respect to the public interface offered by the abstract data type being cast. Thoughtful, negotiated solutions that respect the advertised capabilities of objects often require more finesse than a heavy-handed cast, but they generally result in more robust, portable, and usable code and interfaces.
|