The liabilities of binding rvalues to ref
Jonathan M Davis
jmdavisProg at gmx.com
Thu May 9 18:03:57 PDT 2013
On Friday, May 10, 2013 10:38:47 Manu wrote:
> What were the arguments again against ref const()? You're talking about
> making it clear that the function isn't planning on mutating the given
> rvalue...
> I understand that const is stronger than C++, but is it actually a
> deal-breaker? It's the most logical fit here.
Not being able to differentiate between when it's an rvalue and lvalue causes
some problems, though Andrei understands those issues far better than I do.
I've been able to come up with cases where it would be a problem if you could
have ref on a local variable, but without that, I don't really understand
where you end up with problems with const ref due to not being able to
differentiate between rvalues and lvalues. It's easy to come up with cases with
plain ref (e.g. the example in Ali's talk when a type's opAssign treated
rvalues and lvalues differently, swapping guts with the rvalue and copying from
the lvalue), but I'm not as clear on when it ends up being an issue with
const. The fact that we don't allow ref on anything other than parameters and
return types really simplifies things, so I'm not sure that the situation with
const ref would be anywhere near as bad in D as Andrei thinks that it is in
C++, but I don't know.
However, regardless of all that, the primary problem that I see with using
const ref to indicate that you want to accept rvalues by ref is the fact that
D's const is so restrictive, and there are types where const just plain
doesn't work for them. As such, it strikes me as a bad idea to require const
in order to accept rvalues by ref even if there are no other problems with it.
Now, you could end up with other weird problems if you used auto ref (assuming
that we used auto ref for this) without const and the function _did_ mutate
its argument (we already have that problem with auto ref and templates), but
if you really want the extra protection and can afford it, you can always use
const with it. The problem is the cases where you can't use const. We've been
trying very hard to make it so that const is completely optional precisely
because of how restrictive it is. Requiring it for this seems problematic to
me.
- Jonathan M Davis
More information about the Digitalmars-d
mailing list