Wednesday, July 15, 2009

Episode One: To be or not to be const

Const-correctness is the form of program correctness that deals with the proper declaration of objects as mutable or inmutable. It dictates that all objects should be declared as const unless they need to be modified. It results in clearer, easier to follow code.



In C++, const does not imply that an object's bits cannot be changed (bitwise const), but rather than its logical state does not change (logical const). It's not about optimizations as some may think, but about declaration of intention [1]. By declaring an object as const you let the compiler known that its value is not meant to be changed, and the compiler will enforce such declaration. It's also a form of embedded documentation for future readers.

Sometimes an object logical state does not change, but its bits do (think of an object that provides reference count, cache, ...). Such thing is accomplished by the use of the `mutable` keyword. A member object that is declared as mutable can always be changed, even inside a const member function or by a pointer/reference to const. Another alternative is to "cast the constness away" by means of const_cast. By using it, its possible to turn a pointer/reference to an inmutable object into one to a mutable object. This is legal only if the pointed/referred object was not declared inmutable.

Sometimes following const-correctness may impose an additional burden on the developer, but its benefits outweights the cost. If something is meant to be inmutable, Don't Lie To Your Compiler.

[1] http://www.revergestudios.com/reblog/index.php?n=ReCode.Const

No comments:

Post a Comment