What are the known shortfalls of const
in C++ and C++0x?
The problem with const is the programmers that use it incorrectly our inconsistently
What's wrong with const
is that many programmers don't seem to be able to understand it completely, and a "half-const-correct" project simply does not work. This is what you need to know:
Foo
vs. const Foo
(or Foo const
)Foo&
vs. const Foo&
(or Foo const&
)
Foo*
vs. const Foo*
(or Foo const*
)
Foo* const
and const Foo* const
(or Foo const* const
)void Foo::mutator()
vs. int Foo::accessor() const
iterator
vs. const_iterator
const iterator
and const const_iterator
Migrating to C++ from a language that has no const concept is quite hard, any many fail to see the point.
const
is great. const
is important. const
-correctness is necessary condition for an API to be good.
Yet there are two issue I've had with const
, repeatedly.
There's no way to mark a variable as const
retroactively. You must either declare a variable code, in which case you have to initialize it immediatly. What if the initialization code contains an if
, though? You have the choice of either omitting the const
(undesirably), using operator ?
instead of if
(harms readability). Java get's that right, BTW - const
variables don't have to be initialized right away, they just have to be initialized before they're first read, and they have to be initialized in all branches of an if
.
There's no way to specifiy that an object passed by reference to a function won't change for the duration of the function call. const T& t
does not mean that the object pointed to by t
won't change, but only that the reference t
cannot be used to change it. The compiller still has to assume that any function call which it does not see into might change the object. It some cases, that prevents quite a few optimizations.
The two main issues that I have seen frequent complaints about in newsgroups, are
The need to waste a lot of time on supporting non-const-aware APIs (especially Microsoft's).
The need to define both const and non-const version of a method.
I think the latter could/should be supported by the language.
Possibly in conjunction with support for covariant member function implementations, because both need some way to pick up the type of the this
pointer.
A third issue is that
Cheers & hth.,
One problem is that the language also lets you const_cast it away, which defeats the purpose of using const in the first place.
Most of the answers below state things such as "what is wrong with const
is that X people do Y". Those are not answers but symptoms. Those are not things wrong with const
. There's barely any wrong thing with const
... Those are things wrong with people who can't RTFM.