Skip to content

Instantly share code, notes, and snippets.

@pbackus
Created March 7, 2022 15:45
Show Gist options
  • Save pbackus/b87005c851f30dcd7693a2ae0e0afa84 to your computer and use it in GitHub Desktop.
Save pbackus/b87005c851f30dcd7693a2ae0e0afa84 to your computer and use it in GitHub Desktop.
struct Ref(T)
{
T* ptr;
ref inout(T) deref() inout
{
return *ptr;
}
alias deref this;
}
Ref!T byRef(T)(return ref T lvalue)
{
return Ref!T(&lvalue);
}
auto forward(T)(return auto ref T value)
{
static if (__traits(isRef, value))
return value.byRef;
else
return value;
}
// Can't escape a reference to a local
unittest
{
assert(!__traits(compiles, {
int n = 123;
return n.byRef;
}));
}
// Can modify through a reference
unittest
{
static void modify(Ref!int r)
{
r++;
}
int n = 123;
modify(n.byRef);
assert(n == 124);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment