About
Const correctness revisited…
I have always had a heck of a time reading and figuring out what ‘consts’ apply to. As some of you may well know, you should try to train yourself to use const as early and often as necessary. Read more at Const Correctness to get an idea when and where to use it.
Then I found this gem while reading Scott Meyers Effective C++, hope he won’t get mad me replicating some of it here:
char *hello = “Hello World”; // non const pointer, non const data
const char* hello = “Hello World”; // Non const pointer, const data
char * const hello = “Hello World”; // const pointer, non const data
const char* const hello = “Hello World”; ///const pointer and data
Basically the idea is to draw line on the asterix. If const appear on the left on the line, what is pointed to is const. If the const appear on the right, then the pointer is const.
It also helps to read from right to left too as pointed in the C++ FAQ.
eg, const char* hello —> hello is a pointer pointing to a const data…
and char* const hello —> hello is a const pointer pointing to a non-const data
I have found that the use of const did help me prevent some serious bug a few times; eg, I found myself modifying some part of the code where I shouldn’t. It also helps you think more carefully on designing member functions that are secure, that is, you have the guarantee that the function would not change the data members.
However, I find the use of const such as “const char* const hello” is kinda convoluted and a bit overused… Of course, it’s just my personal opinion and there’s no absolute right or wrong way on this.