Derek Parnell escribió:
On Sat, 07 Mar 2009 23:40:52 -0800, Walter Bright wrote:

I'm still not understanding you, because this is a contrived example that I cannot see the point of nor can I see where it would be legitimately used.

I can see Burton's concern, and I'm very surprised that the compiler allows
this to happen. Here is a slightly more explicit version of Burton's code.

import std.stdio;
void main()
{
  int [] a = new int [1];

   a [0] = 1;

   invariant (int) [] b = cast (invariant (int) []) a;

   writef ("a=%s b=%s\n", a [0], b[0]);
   a [0] += b [0];
   writef ("a=%s b=%s\n", a [0], b[0]);
   a [0] += b [0];
   writef ("a=%s b=%s\n", a [0], b[0]);
}
The problem is that we have declared 'b' as invariant, but the program is
allowed to change it. That is the issue.

As I see it, the cast should fail saying "can't cast a to invariant because a is mutable", because otherwise you are producing a behaviour that doesn't match what the code says.

In:

char c;
int* p = cast(int*)&c;
*p = 5;

there's nothing wrong about the cast because a char can be viewed as an int. But a mutable data cannot be seen as immutable.

Walter, you say "Whenever you use a cast, the onus is on the programmer to know what they are doing." That's true. But if the programmer made a mistake and she wasn't knowing what she was doing, the compiler or the runtime should yell.

For example:

class A { }

class B : A { }

class C : A { }

void foo(A a) {
  C c = cast(C) a;
}

The programmer is sure "a" is really of type "C". If it is, ok, everything works. Now, assuming it is not, this yields a null "c" which fails at runtime if "c" is used (which will be used eventually because that's why we are casting it). The failure is a big one: the program halts. (well, I'd prefer an exception to be thrown, but that's another issue). Now, if you allow a cast from mutable to immutable to continue, the error at runtime will be very subtle and really hard to find, because the program will continue to work but with a wrong behaviour.

Reply via email to