Am 05.03.2011 16:44, schrieb Peter Alexander:
On 5/03/11 1:39 PM, Mafi wrote:
Am 05.03.2011 13:10, schrieb Peter Alexander:
How do you think array assignments in C++ work?

a[i] = x;

a[i] is just *(a + i), i.e. the evaluation of an expression that yields
a temporary, which in this case is an lvalue. Same applies to all other
operator[] overloads.

No, the temporary in this case is not an lvalue. It's an adress whose
value is an lvalue.

(a + i) is an address (type T*)

*(a + i) is a lvalue reference (type T&)


I know. I meant the temporary itself (ie a + i) is not an lvalue; it lies around in some register which should the coder should not explicitly write to. The dereferencing only changed what to do with the result. There's no computation behind derefencing.

The results of operator[] is a reference not a normal value. A reference
is an adress which is always implicitly derefenced when used.
In D we use opIndexAssign anyways.

A reference is not an address. A reference is a synonym for another
object. If that other object is an lvalue then the reference is also an
lvalue.


A reference is nothing else than a pointer which the compiler handles diferent at compile time. Look

/++++++ main.d +++++++++/
import std.stdio;

//extern(C) to avoid mangling
extern(C) void refTest(ref int x);

void main() {
    int a = 5;
    refTest(a);
    a = 7;
    refTest(a);
    a = 42;
    refTest(a);
    writeln("END");
}

/+++++++ test.d ++++++++/
import std.stdio;

extern(C) void refTest(int* x) {
    writefln(" x = %s,  *x = %s", x, *x);
}

/+++++++ compile +++++++/
dmd -c test.d
dmd main.d test.obj
./main

/+++++ output ++++++++/
 x = 12FE44,  *x = 5
 x = 12FE44,  *x = 7
 x = 12FE44,  *x = 42
END

Tested with dmd 2.051 on Win7.
Look reference = pointer + implicite derefence

.......

Reply via email to