Casting away const and invariant

James Dennett jdennett at acm.org
Sun Sep 9 14:24:33 PDT 2007


Janice Caron wrote:
>> It may well be necessary; if it is, the behaviour must be defined
>> so that it _works_.
> 
> No, it's undefined for a reason. It should stay undefined.

You may be missing my point.  I'll try to explain more
clearly below.  The key is *what* is defined/undefined.

> Circumvention is necessary so that you can call library functions
> which are incorrectly declared. For example, if a library function is
> declared as
> 
> int strlen(char[] s); /* erroneous declaration - function does not
> modify the bytes of s */
> 
> then circumventing the normal casting rules would be harmless, because
> no undefined behaviour is being invoked. The key point here is that
> you would have to /know/, with absolute certainty, that strlen() was
> not going to modify the bytes of your string. If you made the wrong
> call ... well, then that's when the undefined behaviour would kick in.

So the cast was *not* undefined at all -- only the act of
modifying after that is undefined.  That's fine.

> No, Walter is absolutely right to make it undefined. And also
> absolutely right to allow circumvention.

You can't do both.  The behavior of the cast must be well
defined, otherwise it does not allow circumvention.  The
result of modification likely should be undefined, but that
is a different matter.

> My only argument is that circumvention should require a different syntax.

I'd agree with that; it's something C++ has almost right
(though backwards with C means that you can const_cast
without being explicit).  D's single cast syntax is rather
a step backwards from C++.

-- James



More information about the Digitalmars-d mailing list