← Back to team overview

unity-dev team mailing list archive

[Ayatana-dev] [C++][Review guidelines] Please avoid casts

 

Hi All,

I'm going to start some emails for review guidelines in C++.

The subject is perhaps a little controversial, but I'm going to explain.

With C++, almost all of the time you can get away without casts [1].  
Sometimes however they are necessary, and I want to go over those

Fistly, please don't use the C-style casts.  These are of the form
   (SomeType)value

C style casts can cause a lot of problems as they are effectively reinterpret 
style casts.

Please use the C++ casts when they are needed.  However using a C++ cast 
doesn't mean that the code is good.  Any time a cast is needed, we should be 
looking at why it is there.

One place it is surely needed is casting from a void* or gpointer in order to 
use the untyped data that is often passed into a callback.  I'd prefer that we 
use reinterpret_cast for these rather than static_cast as it is explicitly "I 
know I'm enforcing my world view on this data pointer, and I know what I'm 
doing."

Casting down an inheritance hierarchy is *bad*.  We shouldn't be doing it.  
Even with a static cast!  Casting down a hierarchy breaks the "open-closed 
principle".  Instead, you should be asking of the code (or coder) as to why 
they are casting down, and what could be done to make the down-cast not 
needed.  Often it is exposing the appropriate methods in the base class, 
although sometimes it is just an indicator that the design needs more work.

To avoid integer division, casting the values to floats are often used.  You 
don't need to cast both the numerator and denominator, only one needs to be a 
float (or double) for the calculation to be non-integral.  It is common 
practice to just cast the denominator using static_cast<float>(value), or to 
use a temporary variable.  Don't be afraid to use temporary variables to make 
the mathmatical expression easier to understand.  Compilers are extremely good 
at optimising away "unneeded" temporaries.

Tim

[1] http://www2.research.att.com/~bs/bs_faq2.html#static-cast

Attachment: signature.asc
Description: This is a digitally signed message part.