Re: const is an overrated concept that is a source of extra typing and maintenance
mattb schrieb:
I have recently heard the above, along with a further statement along
the lines of -
'const is there to stop amateur slip ups. Professionals should know
what a function is expecting and should use that.'
Could I please have some comments on these statements.
1. const is a technical advantage.
Without const, you cannot trivially implement copy-on-write or simply
use the information that your object state did not change.
Without const, there is no reference to const. You cannot call
template<typename T>
T function(const T& a); // assume T can be fat, f.e. an IPv6 address
by using
int t = function(1);
any longer.
Compilers should be able optimize more with const, in particular when
using compile time constant values.
2. const is for free (IDEs should autocomplete it) and prevents lots
of errors
void work(const Container& a, Container& b)
{
assert(a.size() > b.size());
Container::const_iterator j(a.begin());
for(Container::iterator i(b.begin()); i != b.end(); ++i, ++j)
if(compareStuff(*i, *j))
j = b.erase(j); // oops, mistook j for i
}
Remove the const and replace the const_iterator and you will have a
hard time finding the bug. The buggy line works at least with vectors
in g++.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]