www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - opAssign return type

reply Q. Schroll <qs.il.paperinik gmail.com> writes:
When overloading assignment, I've been taught in my C++ course to 
return a reference to the lvalue being assigned to. This is 
easily possible in D, but in Phobos it is used rarely and in Ali 
Çehreli's Book it is neither taught to do so.

Is there any reason to it? To me it seems very obvious to do it 
like in C++.

The question came up in the discussion of a PR:
https://github.com/dlang/dlang.org/pull/1466
Sep 02 2016
parent reply Steven Schveighoffer <schveiguy yahoo.com> writes:
On 9/2/16 1:18 PM, Q. Schroll wrote:
 When overloading assignment, I've been taught in my C++ course to return
 a reference to the lvalue being assigned to. This is easily possible in
 D, but in Phobos it is used rarely and in Ali Çehreli's Book it is
 neither taught to do so.
Sure, you can do this.
 Is there any reason to it? To me it seems very obvious to do it like in
 C++.
I can imagine a reason is to avoid issues with lifetime. It's dangerous to return this as a reference in most cases, because this is implicitly passed by reference even for rvalues. However, for opAssign, you generally are sure you don't have an rvalue. In any case, there's nothing wrong with it technically, it should work. -Steve
Sep 02 2016
parent Q. Schroll <qs.il.paperinik gmail.com> writes:
On Friday, 2 September 2016 at 17:33:22 UTC, Steven Schveighoffer 
wrote:
 On 9/2/16 1:18 PM, Q. Schroll wrote:
 When overloading assignment, I've been taught in my C++ course 
 to return
 a reference to the lvalue being assigned to. This is easily 
 possible in
 D, but in Phobos it is used rarely and in Ali Çehreli's Book 
 it is
 neither taught to do so.
Sure, you can do this.
 Is there any reason to it? To me it seems very obvious to do 
 it like in
 C++.
I can imagine a reason is to avoid issues with lifetime. It's dangerous to return this as a reference in most cases, because this is implicitly passed by reference even for rvalues. However, for opAssign, you generally are sure you don't have an rvalue.
Interestingly the compiler does not allow rvalue = expr but it does however allow rvalue.opAssign(expr).
 In any case, there's nothing wrong with it technically, it 
 should work.

 -Steve
There is no possibility to enforce some method is only available for lvalue this?
Sep 02 2016