What should opAssign return, finally answered!

Steven Schveighoffer schveiguy at yahoo.com
Tue Oct 23 07:00:02 PDT 2007


"downs" <default_357-line at yahoo.de> wrote in message 
news:ffkf66$6cr$1 at digitalmars.com...
> Charles D Hixson wrote:
>> What I would expect is:
>>
>> class A
>> {
>>   A opAssign(A a)
>>   {
>>      // do stuff here
>>      return this;
>>   }
>> }
>>
>> but the only examples that I can find (variant.d) return *this ... which
>> leaves me quite confused.  Is this something special that Variant is
>> doing to allow it to handle multiple types (I didn't follow the
>> internals), or do I have what is supposed to be returned wrong?
> Variant is a struct.
> The this of a struct is a pointer.
> Ergo it has to dereference it, since opAssign returns the assignee for
> purposes of assignment chaining (a=b=c).
>
> Hope that clears things up.
> --downs

To take it one step further, what you have is correct for classes, what 
Variant has is correct for structures.  The this member (which strangely, I 
can't find the documentation for on digital mars' site) is a reference for a 
class, and is a pointer for a struct.  Since the return value for opAssign 
on a class is a reference, you return this.  Since the return value for 
opAssign is a struct, not a pointer to a struct, you must return *this.

-Steve 




More information about the Digitalmars-d-learn mailing list