Assignment and down-casting

Yigal Chripun yigal100 at gmail.com
Sat Mar 7 09:59:04 PST 2009


I just read this article by Dennis Richie posted on the NG [1], and I 
wanted to discuss a way to solve the const return issue.

here's some (general) code:

class A {}
class B : A {}

A func (A a) {
   .. do stuff ..
   return a;
}

void main() {
   B b = new B;
   A a1 = func(b);
   B a2 = cast(B) func(b); // will not compile with explicit cast
}

the explicit downcast could be removed if the compiler inserted the 
down-cast implicitly - assigning null or throwing if the down-cast fails.

this can be applied to constancy since const is super type of both 
immutable and mutable. I don't know how a const pointer/reference is 
implemented in D so assume that pointers to const objects have a certain 
bit set. (constancy runtime type)

// create a const object - bit is set
const T* cptr = cast(const T*) new Struct;
// create mutable object - bit unset
T* ptr = new Struct; // bit is unset

on assingment the bit is preserved and cannot be unset:
T* a = ptr; // bit unset
T* b = cptr; // fails - bit cannot be unset
const T* c = cptr; // bit is set
const T* d = ptr;  // bit remains unset

the second case fails by either assinging null to be or by throwing an 
exception.

invariant can use a different bit.

let's say we have:

const T foo(const T a, U b); // foo returns a

const T cptr = ...; //const object
       T ptr  = ...; // mutable object

T res = foo (cptr, something); // fails
T res = foo (ptr, something); // *works*
const T res = foo (cptr, something); // bit set for res
const T res = foo (ptr, something); // bit unset for res

just as before, the first foo fails by evaluating to null or by 
exception and the second foo works since the bit was never set so 
there's no problem "downcasting" to a regular, mutable, pointer/ref.

What do you think?

[1] http://www.lysator.liu.se/c/dmr-on-noalias.html



More information about the Digitalmars-d mailing list