Force lvalue (`cast(ref)`)

IchorDev zxinsworld at gmail.com
Wed Jan 22 08:58:56 UTC 2025


Sometimes you want an rvalue to bind to `ref`, but the compiler 
can’t be sure the reference isn’t escaped. But if you know that 
the reference won’t be escaped, or you don’t care if your code is 
safe at all, you can use `cast(ref)` to forcibly turn an rvalue 
into an lvalue:
```d
ref x = cast(ref)10;
x++; //10 exists for the duration of this function. If this 
function returns x by reference, it is undefined behaviour.
auto y = returnPassedRef(cast(ref)24);
y++; //24 exists for the duration of the function it was created 
in, so `returnPassedRef` safely returned it. If this function 
returns the reference however, it is undefined behaviour.
```
The cast is `@system `. If the lvalue reference is escaped, it is 
undefined behaviour.
Passing a newly made lvalue into `return ref` parameters should 
probably issue a warning.

This feature is useful in writing low-level code where safety is 
manually verified, especially when interfacing with C++ libraries.

Possible alternative: the hideous `__lvalue`. However, `__rvalue` 
is dissimilar in that it is not `@system` and does not produce 
undefined behaviour, whereas casts are often `@system `, so 
perhaps the dissimilar syntax is a good reflection of the 
differences between the two.


More information about the dip.ideas mailing list