Const correctness is, in general, important -- but the examples you are using are not really the places it matters. For example:
void foo (const int i, const string s)
I would be so bold as to declare this prototype wrong. If you just had the prototype
void foo (int i, string s)
then this is already a promise not to modify the values the user passes in for i
and s
. (since you get copies of those values, rather than references to the original) So, the only thing that const
does in this case is to request the compiler to complain if you accidentally tried to modify i
or s
. But there are other ways to achieve this effect -- it doesn't really have any business being exposed externally.
Now, the following use of const
would actually be useful:
void foo (int i, const string &s)
this retains your promise not to modify s
, but now you get a performance benefit because it no longer involves a copy of s
being made.
Some of the other uses are fine:
const size_t size = vec.size();
this is good. (once you replace uint
with size_t
) There isn't a performance benefit to it here, but it's self-documenting and can protect you against silly accidents.
const string s2 = s1 + "hello ";
This is good as well. Although again I might make it a reference instead:
const string &s2 = s1 + "hello ";
This one
operator const bool () const { return ...; }
is most irrelevant. You should probably implement operator bool
instead of operator const bool
even if for no reason other than the former is what people expect.
But it could matter for classes who have non-const versions. Returning const
, then is not a matter of taste or style, but instead a declaration "I'm going to return to you a new object, but you're not allowed to call any of its non-const functions". This is usually a bad idea -- only make it const
if you really mean to make that declaration.