reference variables don't exist, but can simulate them

NonNull non-null at use.startmail.com
Sun Jun 28 21:01:36 UTC 2020


On Sunday, 28 June 2020 at 20:59:59 UTC, NonNull wrote:
> Using gdc (Ubuntu 8.4.0-1ubuntu1~18.04) 8.4.0
> Please criticize:
>
> struct refer(T) {
>   T* ptr;
>   this(ref T x) { ptr = &x; }
>   ref T _() { return *ptr; }
>   alias _ this;
>   string toString() { import std.conv; return to!string(*ptr);  
> }
> }
>
> This will make a reference variable (simulation). [ toString() 
> is just for writeln. ]
>
> void main() {
>     int i = 100;
>     refer!int j = i;
>     j = 3;
>     writeln(i);
>     i = 100;
>     writeln(j);
>     j += 3;
>     writeln(i);
>     refer!int k = j;
>     writeln(k);
> }
>
> And a refer!int can be returned as it is just a value. 
> Returning one that contains a pointer to a local variable leads 
> to a compilation error.

* does not lead to a compilation error



More information about the Digitalmars-d-learn mailing list