Who`s Afraid to Be Const Correct? Help Your Compiler Help You - The Compiler is Your Friend
(Page 2 of 4 )
Maybe you haven’t given it much thought, but returning a const value from a function can help you catch errors. Imagine we have a Vector class and we would like to be able scale a vector object by multiplying it with a float:
class Vector3 {
public:
...
Vector3 const operator * (float factor) const;
...
};
Because ‘operator *’ returns a const value, the compiler will prevent us from writing code like:
(vectA * PI) = vectB;
simply because you cannot assign ‘vectB’ to a constant value! The first thing you will think is that you would never write code like that, but bugs are introduced in silly ways… at least my bugs often turn out to be silly and laugh at me.
Have you ever been bitten by this bug?
if (valueA = false) { … }
The compiler won’t complain because it is legal to write code like this:
bool bar( ) {
bool result;
if (!(result = foo()) ) { … }
return result;
}
Therefore you will find experienced coders who have been bitten one time too many coding this instead:
if (false == valueA) { … }
Because the compiler does complain about:
if (false = valueA) { … }
Surely you agree the statement above makes no sense… same goes for:
if ( (vectA * PI) = vectB ) { … }
when you actually meant:
if ( (vectA * PI) == vectB ) { … }
Not everybody agrees on this though. John Lakos for example states that since returned values are copies anyway, exploiting the notion of a const versus a non-const temporary value is typically unnecessary and can interfere with template instantiation [Lakos].
Personally I prefer the compiler to help me catch my mistakes. Temporary values (rvalues) are not trivial, and we will take a closer look at them in the next article.
Next: Why Use the Compiler to Catch Errors? >>
More C++ Articles
More By J. Nakamura