Fully transitive const is not necessary

Janice Caron caron800 at googlemail.com
Wed Apr 2 23:43:30 PDT 2008


On 02/04/2008, Sean Kelly <sean at invisibleduck.org> wrote:
> I know you like to talk about the unreliability of const in C++ because of
>  const_cast and the like, but in my opinion those are theoretical objections
>  because I've never encountered even a single use of const_cast in actual
>  code.

One anecdote is not statistically significant. The company I work for
once wasted six weeks while six programmers tracked down a
multithreading bug, an obscure race condition that brought down our
server after some random period in time measured in days. We finally
found and fixed it, but it turns out that particular bug could never
have happened in D. Transitive const would have stopped it dead. And
yes, I know, one anecdote is not statistically significant. I just
thought I'd mention, there are other stories.

I have used const_cast, but it is rare. But that's kinda the point -
the thing about const_cast is that not that you're supposed to use it,
it's that other forms of cast won't accidently cast away constancy.
For example:

    class C {};
    const C c;
    C d = static_cast<C>(c); //ERROR

Trouble is, legacy casting still works:

    C e = (C)c; //OK

So the deal is, static_cast<T> is safer than <T> because it preserves
const correctness (in C++ terms). const_cast<T> is only necessary for
those rare cases where you actually need to change the constancy. At
least - that was the theory. In practice, it never worked, because
they forgot to deprecate (T).



More information about the Digitalmars-d mailing list