Const ref and rvalues again...
Malte Skarupke
malteskarupke at web.de
Thu Oct 18 16:39:47 PDT 2012
On Thursday, 18 October 2012 at 06:11:26 UTC, monarch_dodra wrote:
> On Thursday, 18 October 2012 at 04:30:17 UTC, Jonathan M Davis
> wrote:
>> On Thursday, October 18, 2012 06:24:08 jerro wrote:
>>> What would be the problem with const ref taking rvalues?
>>
>> Read the thread that I already linked to:
>>
>> http://forum.dlang.org/thread/4F84D6DD.5090405@digitalmars.com
>>
>> - Jonathan M Davis
>
> I read the thread, and not a single one of the "problematic
> cases" are actually valid C++.
>
> Yes: the faulty MSVC has taught people to do retarded things,
> or be afraid of things that were illegal to begin with (in
> particular, pass an rvalue to a ref, WHICH IS ILLEGAL IN C++),
> such as "increment(5)".
>
> There is actually nothing wrong with creating a temporary when
> something is bound to a const ref, provided the compiler
> follows the rules:
>
> *Only LValues with an EXACT type match may be passed to a
> reference.
> *In regards to *const* references, RValues may be copied in a
> temporary, and that temporary bound the the ref.
>
> I'm not saying we particularly *need* this in D (C++ has a "by
> ref" paradigm that makes it more important, but D *rarelly*
> ever passes by const ref).
>
> But if the compiler respects the above two rules (which it
> should), then RValue to const ref is both perfectly doable and
> safe (as safe as refs get anyways).
The problem with binding rvalues to const ref is that you could
take and store the address of it. That's why I'd recommend using
"in ref" instead.
@Jonathan: I had already read the linked discussion. There are
many valid points in there, but also many invalid ones (as
monarch_dodra has pointed out). But I think all problems in that
thread should be solved by using "in ref" instead of "const ref"
because then you'd be sure that the passed-in temporary can not
escape the current function.
@foobar: I like the idea, but it's probably going to break down
in many cases. If you have a non-trivial copy constructor you
want the ability to have complete control over when it gets
copied and when it doesn't. I just don't trust compilers enough
to think that they'd always make the same choice that I'd make.
And also about losing semantic information: That's why I proposed
the second point: Give the user the option to provide a function
which should be preferred for rvalues. That way you don't lose
semantic information.
More information about the Digitalmars-d
mailing list