D Classes Passed By Reference or Value?

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Aug 16 16:31:45 PDT 2015


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



More information about the Digitalmars-d-learn mailing list