TITLE: a rationale for static_cast (Newsgroups: comp.std.c++, 26 Apr 2000) HOLTZ: pholtz@ix.netcom.com > Here is an example of resources, how they are loaded and released int > the Macintosh environment. Much code is snipped. > > PicHandle pictureHdl = GetPicture(rPictureResourceID); > ... > HNoPurge((Handle) pictureHdl); > DrawPicture(pictureHdl,&pictureRect); > HPurge((Handle) pictureHdl); > ReleaseResource((Handle) pictureHdl); > > StringHandle stringHdl = GetString(rStringResourceID); > ... > DrawString(*stringHdl); > > ReleaseResource((Handle) stringHdl); > > This is very Macintosh oriented, but when you load reasources they are > usually of the type that you load, a picture handle is "PicHandle", a > string handle is "stringHdl". When we operate with these handles, > sometimes we use the native type, and sometimes we need to 'upgrade' the > handle to a generic "Handle" type. > > HNoPurge(static_cast(pictureHdl)); > DrawPicture(pictureHdl,&pictureRect); > HPurge(static_cast(pictureHdl)); > ReleaseResource(static_cast(pictureHdl)); > > How does static_cast add anything to this code? ADLER: Darin Adler It makes it easy to search for such casts, which are common hiding places for errors, since you could accidentally have said "*pictureHdl" instead of "pictureHdl", for example. It would then compile and fail at runtime. In my Macintosh code, I make inline functions like: inline Handle AsHandle(PicHandle h) { return static_cast(h); } inline PicHandle AsPicHandle(Handle h) { return static_cast(h); } I overload for various handle types. Then write the code like this: HNoPurge(AsHandle(pictureHdl)); DrawPicture(pictureHdl,&pictureRect); HPurge(AsHandle(pictureHdl)); ReleaseResource(AsHandle(pictureHdl)); This is safer than any kind of cast. If I accidentally pass an expression of the wrong type, I get a compile time error. Of course, in most of my programs I have even higher level abstractions, but all the styles avoid casts as much as possible. The few casts I have are usually in inline functions. Converting from casts to inline functions like this in existing code for projects I've taken on as a consultant typically results in finding and fixing a significant number of previously undetected errors in the code base that I'm about to work on. _______________________________________________ cpptips mailing list http://cpptips.hyperformix.com