The Status of Const

Walter Bright newshound2 at digitalmars.com
Fri Aug 13 18:41:27 PDT 2010


Tomek Sowiński wrote:
> Walter Bright napisał:
> 
>> But there is a solution:
>>
>> const(Object)* o;
> 
> Interesting. How do you cook that with polymorphism? This doesn't work:
> 
> interface I { }
> class A : I {}
> 
> void main() {
>     immutable A a = new immutable(A);
>     immutable(A)* ap = &a;
>     // Error: cannot implicitly convert expression (ap) of type immutable(A)* to immutable(I)*
>     immutable(I)* ip = ap;
> }

The polymorphic bit works on the reference, not the pointer to the reference. A 
conversion to an interface actually is a change in the bits, so a pointer to an 
A cannot also be pointed to by a pointer to I.


> BTW, should this work?:
> immutable(A)* ap = &new immutable(A);
> Now it fails with "new immutable(A) is not an lvalue".

Right. You can't take the address of an rvalue. What you do is:

immutable(A) a = new immutable(A);
immutable(A)* ap = &a;
immutable(I) i = a;
immutable(I)*pi = &i;

Yes, there's another piece of memory involved there (the storage for a, and i).


More information about the Digitalmars-d mailing list