D Classes Passed By Reference or Value?
Nicholas Wilson via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sun Aug 16 17:46:15 PDT 2015
On Sunday, 16 August 2015 at 23:40:41 UTC, Brandon Ragland wrote:
> 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
Yes.
void doStuff(ref MyClass a, ref MyClass b, ref MyClass c, bool d)
{
if (d)
b = a;
else
c = a;
}
void main(string[] args)
{
auto a = new MyClass(); a.x = 1;
auto b = new MyClass(); b.x = 2;
auto c = new MyClass(); c.x = 3;
assert(a !is b);
assert(a.x == 1);
assert(a !is c);
assert(b.x == 2);
assert(c !is b);
assert(c.x == 3);
doStuff(a,b,c,true);
assert(a is b);
assert(b.x == 1);
b.x = 2;
assert( a.x == 2);
assert(a !is c);
assert(c.x == 3);
doStuff(a,b,c,false);
assert(a is c);
assert(c.x == 2);
}
More information about the Digitalmars-d-learn
mailing list