Thread overview
opAssign return type
Sep 02, 2016
Q. Schroll
Sep 02, 2016
Q. Schroll
September 02, 2016
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
September 02, 2016
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
September 02, 2016
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?