3

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

When should static_cast, dynamic_cast, const_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.

Community
  • 1
  • 1
chrisp451
  • 85
  • 1
  • 6
  • 2
    Using static_cast to downcast pointers is fine, and recommended if you know that it is the right sub-class that you're casting to. – Peter Alexander Mar 17 '10 at 21:16
  • That's an appropriate use of static_cast. I'm looking for a tool that will detect inappropriate use (where it's the wrong sub-class that I'm casting to). – chrisp451 Mar 17 '10 at 21:27
  • 1
    The problem is that the particular case where `static_cast` scape the information available in the code (you may know from invariants in your design that the cast will be correct even if the information is not present in code) – David Rodríguez - dribeas Mar 17 '10 at 22:45

3 Answers3

5

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
  • 1,656
  • 15
  • 37
4

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
  • 1,022
  • 6
  • 7
0

Boost offers polymorphic_pointer_downcast() and polymorphic_downcast() functions, which act like static_cast but will assert (typically only in debug builds) if the equivalent dynamic_cast fails.

See http://www.boost.org/doc/libs/1_61_0/libs/conversion/cast.htm for details.

LLFF
  • 31
  • 3