Const ref and rvalues again...
martin
kinke at libero.it
Sun Oct 21 15:18:40 PDT 2012
On Friday, 19 October 2012 at 00:03:49 UTC, Timon Gehr wrote:
> Const is different in D and in C++. Relating const and rvalues
> is arbitrary and does not make a lot of sense.
It's actually pretty much the same concept in both languages
except for the transitiveness in D. An implicit rvalue => _const_
ref conversion is something completely different than an rvalue
=> mutable ref conversion, and this distinction is sadly largely
lost in the linked thread, which is why I tried to re-initiate
the discussion with another recent thread. Arguments passed by
mutable references are expected to be changed by the called
function, so passing rvalues does indeed not make much sense in
that case (side effects may get lost, quite possibly
unintentionally).
On Friday, 19 October 2012 at 01:26:35 UTC, Malte Skarupke wrote:
> This is about finding a way that you can define a function
> which safely accepts lvalues and rvalues without having to make
> a copy.
EXACTLY! Something telling the compiler: pass the argument by
const reference instead of a costly const copy, if possible. So
for an lvalue, pass directly its address; for an rvalue, allocate
the temporary on the stack and then pass its address:
<code>
T foo(in ref T bla) { return bla; }
T lvalue;
foo(lvalue); // fine
foo(foo(lvalue)); // error: rvalue!
// required compiler magic:
immutable tmp = foo(lvalue); foo(tmp);
/* possibly in dedicated scope for
immediate destruction of tmp */
</code>
Currently having to allocate all rvalues manually is frankly both
ugly and a pain in the ass, as would be the other alternative:
overloading foo().
On Friday, 19 October 2012 at 03:49:56 UTC, jerro wrote:
> My point was that saving an address of a const ref parameter is
> already unsafe if you call the function with a local variable
> as the parameter. If this behavior seems problematic to you
> when it concerns rvalues, it should seem equally problematic
> when it comes to local variables. It doesn't make sense to make
> passing rvalues as const ref parameters illegal because of this
> problem, when passing local variables causes the same problem
> and is legal. [...]
> The only case I can think of when passing a local variable as
> const ref is safe, but passing an rvalue wouldn't be, is when
> the called function returns the address of the const parameter
> (or assigns it to some other ref parameter).
Exactly my thoughts regarding this escaping aspect, which I don't
see as big issue. The compiler magic illustrated in the previous
example without dedicated scope for temporaries would make
passing rvalues exactly as safe/unsafe as passing local variables.
More information about the Digitalmars-d
mailing list