Remaining const niggles #1 - Custom POD types

Janice Caron caron800 at googlemail.com
Sun Feb 17 23:44:18 PST 2008


On 18/02/2008, Christopher Wright <dhasenan at gmail.com> wrote:
> > One cannot "unconst" something without an explicit cast. This is
> > precisely what I aim to avoid. The explicit cast should be
> > unnecessary, whether within opImplicitCast (or any other function), or
> > not.
>
> Yes you can:
>
> struct Something {
>     int member; //...
>     Something opImplicitCast() const {
>        Something s;
>        s.member = this.member;
>        return member;
>     }
> }

Ah, but you're not thinking ahead. Right now, that may well work, but
in the future, when the "struct const bug" is fixed, it will stop
working. You're basically exploiting a bug there.

It's like this - if s is an instance of const(S), then, not only is s
const, but /every member of s is also (transitively) const. Right now,
the compiler doesn't know that, because it's a bug, but it will be
fixed before too long. (It has to be, as it allows one to break
constancy). Once that bug is fixed, you will no longer be able to do

    s.member = this.member;

because this.member will have type const(U), for some U, while
s.member will have type U, and (...and this is the whole point of this
thread...) const(U) will not implicitly cast to U. So sure, your
example works today. But it most likely will not work tomorrow. The
only way to guarantee that it will work post-bug-fix would be to write

    s.member = cast(something)(this.member);

instead.


> Whoever designed the struct can tell you whether it's safe to cast a
> const form of it to a mutable form.

They can tell you their /intent/, but only the compiler can absolutely
guarantee it. The compiler can /prove/ whether or not a given type is
safe to copy.


> You need to tell the compiler whether it's okay to copy a const struct
> into a mutable one.

First off, let me remind everyone that casting away const is undefined
in D. Let me stress that point - /undefined/. That doesn't mean "use
with caution", it means you should never, ever do it, except to call
library functions which have been incorrectly declared.

The compiler knows (as in, can prove), what is safe and what isn't. It
is therefore the compiler's job to do that. It is absolutely not a
good idea to tell programmers that they need to start resorting to
constructions with undefined behaviour.



More information about the Digitalmars-d mailing list