views:

157

answers:

2

The answers to the following question describe the recommended usage of static_cast, dynamic_cast, and reinterpret_cast in C++:

http://stackoverflow.com/questions/332030/when-should-static-cast-dynamic-cast-and-reinterpret-cast-be-used

Do you know of any tools that can be used to detect misuse of these kinds of cast? Would a static analysis tool like PC-Lint or Coverity Static Analysis do this?

The particular case that prompted this question was the inappropriate use of static_cast to downcast a pointer, which the compiler does not warn about. I'd like to detect this case using a tool, and not assume that developers will never make this mistake.

+3  A: 

Given that there is no reliable way of telling what type the pointer points to at compile time, this is a pretty hard problem to catch at compile time.

The simplest method is to do the catch at run-time, using a macro "safe_cast" which compiles to a dynamic_cast with an assert in debug, and a static_cast in release.

Now, during debugging, if the cast is inappropriate, the dynamic cast will return NULL, and assert. There is also no overhead during release.

Simon Parker
+3  A: 

Visual studio has warnings for some of these. C4946, for example. They're mostly turned off by default though.

http://msdn.microsoft.com/en-us/library/23k5d385.aspx

Michael