| |
| Posted by Ali Çehreli in reply to zjh | PermalinkReply |
|
Ali Çehreli
| On 12/11/22 01:25, zjh wrote:
> On Sunday, 11 December 2022 at 04:36:45 UTC, thebluepandabear wrote:
>
>> "The main reason for this limitation is the fact that a function
>> taking a ref
>> parameter can hold on to that reference for later use, at a time when
>> the rvalue
>> would not be available."
>>
>
>
> I only know that `rvalue` is a temporary value that will not be used,
Temporary values can be used but they should not be stored for later. In this context, if the ref parameter were also 'scope', we should be able to pass rvalues. (See below.)
> while `ref` is omitting a pointer.
Yes, although it is still a pointer behind the scenes, 'ref' is syntax that avoids pointers.
However, the situation has changed in D: It has been possible to pass rvalues by reference through the magic of 'in' parameters. This currently requires the -preview=in compiler switch, which makes 'in' parameters imply 'const scope':
https://dlang.org/spec/function.html#in-params
import std.stdio;
struct S {
string id;
}
void foo(in S s) {
writeln("foo received ", s.id);
}
void main() {
auto s = S("lvalue");
foo(s);
foo(S("rvalue"));
}
Prints
foo received lvalue
foo received rvalue
On can add a copy constructor to S to see whether 'in' is by-copy or by-value.
Ali
|