digitalmars.D.learn - opAssign return type
- Q. Schroll (8/8) Sep 02 2016 When overloading assignment, I've been taught in my C++ course to
- Steven Schveighoffer (8/14) Sep 02 2016 I can imagine a reason is to avoid issues with lifetime. It's dangerous
- Q. Schroll (6/26) Sep 02 2016 Interestingly the compiler does not allow rvalue = expr but it
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
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
On Friday, 2 September 2016 at 17:33:22 UTC, Steven Schveighoffer wrote:On 9/2/16 1:18 PM, Q. Schroll wrote:Interestingly the compiler does not allow rvalue = expr but it does however allow rvalue.opAssign(expr).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. -SteveThere is no possibility to enforce some method is only available for lvalue this?
Sep 02 2016