Simulating reference variables using `alias this`
Carl Sturtivant via Digitalmars-d
digitalmars-d at puremagic.com
Wed May 10 10:12:11 PDT 2017
Here's the beginning of an interesting little experiment to
simulate reference variables using `alias this` to disguise a
pointer as a reference. Could add a destructor to set the pointer
to null when a reference goes out of scope.
```
struct reference(T)
{
T* ptr;
this(ref T x)
{
ptr = &x;
}
import std.exception : enforce;
ref T cnvrt() @property
{
enforce( ptr !is null);
return *ptr;
}
ref T cnvrt(T x) @property
{
enforce( ptr !is null);
return *ptr = x;
}
alias cnvrt this;
}
void main()
{
int i;
auto ri = reference!int(i);
auto ri2 = reference!int(ri);
assert(ri.ptr==ri2.ptr);
i = 99;
assert(i==ri && i==ri2 && ri==ri2);
ri = 100;
assert(i==ri && i==ri2 && ri==ri2);
ri2 = 101;
assert(i==ri && i==ri2 && ri==ri2);
}
```
More information about the Digitalmars-d
mailing list