cast(A)b is not an lvalue

Ali Çehreli acehreli at yahoo.com
Wed Dec 26 09:13:13 PST 2012


On 12/26/2012 09:05 AM, Namespace wrote:
>> I can answer the question in the subject line without looking at
>> dpaste: Yes, in many cases the result of a cast operation is an
>> rvalue. It is a temporary that is constructed at the spot for that
>> cast operation.
>>
>> Imagine casting an int to a double. The four bytes of the int is
>> nowhere close to what the bit representation of a double is, so a
>> double is made at the spot.
>>
>> Ali
>
> My question is: Should not work all three?
> IMO: yes.

Here is the code:

import std.stdio;

static if (!is(typeof(writeln)))
	alias writefln writeln;

class A { }
class B : A { }

void foo(ref A a) { }

void main()
{
	A a = new A();
	A ab = new B();
	B b = new B();
	
	foo(a);
	foo(ab);
	foo(b); // < compile error
}

foo() takes a class _variable_ by reference (not a class _object_ by 
reference). Since b is not an A variable, one is constructed on the spot.

Imagine foo() actually does what its signature suggest:

void foo(ref A a) {
     a = new B();
}

That line above is an attempt to modify the caller's rvalue.

Ali


More information about the Digitalmars-d-learn mailing list