Classes new'd inside for loop are all the same instance?

Meta via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Sep 8 06:17:35 PDT 2016


On Thursday, 8 September 2016 at 12:36:29 UTC, drug wrote:
> &c is address of the variable c, that is allocated on the stack 
> and has the same address on every iteration
> cast(void*)c return the value of variable c that is address of 
> a class instance and is different for every iteration
>
> in other words
> &c is address of pointer
> cast(void*)c is the pointer itself

Yes, thank you. I'll just add that in D (as well as in Java and 
C#), while classes are always reference types and the type of `c` 
in `C c = new C();` will be reported as C, it's actually more of 
a hidden type, "reference to a C". These references are always 
passed by value.

c (reference to a C)     value pointed at by c
     on the stack              on the heap
     [0x00002450]    ...      [0x00008695]
           |                        ^
           |________________________|


For example:

class C
{
     string name;
}

void setName(C c)
{
     c.name = "bob"; //This change will be seen outside setName
     c = new C("jim"); //This change will not
}

void setNameRef(ref C c)
{
     c.name = "bob"; //This change will be seen outside setNameRef
     c = new C("jim"); //This change will also be seen outside 
setNameRef
}

In `setName` c (which is actually a reference to a C) cannot be 
rebound as the reference is passed by value into the function. 
However, c.name can still be modified as you are modifying the 
value pointed at by the reference, not the reference itself.

In `setNameRef` you can modify both, because c is passed by ref, 
meaning that there is now a double-indirection. Thus, you can 
modify both c and the value pointed at by c.


More information about the Digitalmars-d-learn mailing list