D Classes Passed By Reference or Value?

Brandon Ragland via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Aug 16 16:40:40 PDT 2015


On Sunday, 16 August 2015 at 23:31:46 UTC, Ali Çehreli wrote:
> On 08/16/2015 04:13 PM, Brandon Ragland wrote:
>
> > That makes more sense. Though it does make the ref method
> > signature unclear, as it only applies to literals at this
> > point?
>
> As long as the returned object will be valid after the function 
> leaves, it can be anything: one of the ref parameters, a 
> module-level variable, etc.
>
> > Would you still need the ref signature for method parameters
> > for classes to avoid a copy? Such that I could work on the
> > class itself, and not a copy.
>
> Obviously, you meant "the object itself."
>
> > //This is reference?
> > void doStuff(ref MyClass mc){
> > return;
> > }
>
> Yes, that's a reference to a class variable. Since class 
> variables are references anyway, unless intended, there is one 
> too many level of indirection there. (Although, it is valid and 
> it may exactly be what is needed.)
>
> > or would this also be a valid reference type:
> >
> > //This is a copy?
> > void doStuff(MyClass mc){
> > return;
> > }
>
> That's the normal way of doing it. mc is class reference to an 
> object that was presumably created somewhere else.
>
> Ali

If I understand you correctly than:

void doStuff(MyClass mc){
mc.x = 7;
}

Would be working with the reference to the object instantiated 
elsewhere. This would NOT be a copy of the object.

That would mean that (ref MyClass mc) is the equivalent to a 
pointer to a pointer (sorta, though these are references, same 
idea follows).

-Brandon


More information about the Digitalmars-d-learn mailing list