[ Team LiB ] |
![]() ![]() |
Gotcha #39: Casting Incomplete TypesIncomplete class types have no definition, but it's still possible to declare pointers and references to them and to declare functions that take arguments and return results of the incomplete types. This is a common and useful practice: class Y; class Z; Y *convert( Z * ); The problem arises when a programmer tries to force the issue; ignorance is bliss only to a certain extent: Y *convert( Z *zp ) { return reinterpret_cast<Y *>(zp); } The reinterpret_cast is necessary here, because the compiler doesn't have any information available about the relationship between the types Y and Z. Therefore, the best it can offer us is to "reinterpret" the bit pattern in the Z pointer as a Y pointer. This may even work for a while: class Y { /* . . .*/ }; class Z : public Y { /* . . .*/ }; It's likely that the Y base class subobject in a Z object has the same address as the complete object. However, this may not continue to be the case, and a remote change could affect the legality of the cast. (See Gotchas #38 and #70.) class X { /* . . .*/ }; class Z : public X, public Y { /* . . .*/ }; The use of a reinterpret_cast will probably cause the delta arithmetic to be "turned off," and we'll get a bad Y address. Actually, the reinterpret_cast is not the only available choice, since we could have used an old-style cast as well. This may initially seem the better choice, because an old-style cast will perform the delta arithmetic if it has enough information at its disposal. However, this flexibility actually compounds the problem, because we may get different behavior from the ostensibly same conversion, depending on what information is available when the conversion is defined: Y *convert( Z *zp ) { return (Y *)zp; } // . . . class Z : public X, public Y { // . . . // . . . Z *zp = new Z; Y *yp1 = convert( zp ); Y *yp2 = (Y *)zp; cout << zp << ' ' << yp1 << ' ' << yp2 << endl; The value of yp1 will match that of either zp or yp2, depending on whether the definition of convert occurs before or after the definition of class Z. The situation can become immeasurably more complex if convert is a template function with many instantiations in many different object files. In this case, the ultimate meaning of the cast may depend on the idiosyncrasies of your linker. (See Gotcha #11.) The use of reinterpret_cast is preferable to that of an old-style cast, in this case, because it will be more consistently incorrect. My preference would be to avoid either. ![]() |
[ Team LiB ] |
![]() ![]() |