is opOpAssign returning a value less than ideal ?

Jonathan M Davis newsgroup.d at jmdavisprog.com
Thu Nov 8 06:01:57 UTC 2018


On Wednesday, November 7, 2018 10:45:07 PM MST Jonathan M Davis via 
Digitalmars-d-learn wrote:
> On Wednesday, November 7, 2018 9:28:19 PM MST Codifies via Digitalmars-d-
>
> learn wrote:
> > I noticed that opOpAsign allows you to return a value...
> >
> > this means I can do this (return a node from my list class when
> > adding a new node)
> > ```
> > anode = alist ~= &someData;
> > ```
> > to me this looks a little unusual (but to be fair I can live with
> > it)
> >
> > being as when its used like this:
> > ```
> > alist ~= &someData;
> > ```
> > you need to find out what the ~ operator does anyway, I don't
> > think it harms readability
> >
> > any thoughts?
>
> It's common practice in C++ to have the various assignment operators
> return a reference to the object being assigned to so that the operations
> can be chained, and I don't see why the situation in D would be any
> different. But if for whatever reason, you don't want to do the same with
> your types, you can always just make those operators void. Either way,
> the fact that an assignment operator returns a reference to the object
> doesn't require you to then actually use it for anything. It just allows
> folks to do so if they think that it's appropriate in a particular piece
> of code. Sometimes, it's useful; often it isn't, but if the return type
> is void, then you can't do it even in the cases where it would be useful.

Rereading what you wrote, are you asking whether it's reasonable to return a
value instead of a reference? Personally, I don't think that that's good
design at all, but I also don't see any reason for the compiler to prevent
it.

Personally, I think that the default design should be to return by ref.
Returning void is less than ideal but isn't necessarily bad, depending on
the situation (especially if we're not talking about a general purpose
library). However, I expect that returning non-void by value rather than by
ref is rarely -if ever - going to be a good design choice. It's just going
to be confusing and not particularly useful.

- Jonathan M Davis





More information about the Digitalmars-d-learn mailing list