Anyway to achieve the following

Carl Sturtivant sturtivant at gmail.com
Sun Aug 15 21:53:14 UTC 2021


On Sunday, 15 August 2021 at 07:10:17 UTC, JG wrote:
> Hi,
>
> This is exactly the behaviour I was trying to obtain.
>
> It however comes with a fair amount of overhead, as can be seen 
> in the following llvm ir:
>
> [...]

What you are asking for are reference variables. C++ has them: 
the example here illustrates the behavior you want.
https://www.geeksforgeeks.org/references-in-c/

D does not have them, as mentioned above:
https://forum.dlang.org/post/mailman.2714.1628875187.3446.digitalmars-d-learn@puremagic.com

So to get the behavior you want, they have to be simulated, which 
is what this does:
https://forum.dlang.org/post/lcrrnszslpyazoziyicb@forum.dlang.org

Next version: no `toString` and storage passed in by reference 
rather than by pointer.

     ```
     struct S {
       int x = 1234;
     }

     void main() {
       import std.stdio;
        S s;
        auto p = &s.x;
        //construction of a using &(s.x)
        auto a = Ref!(int)(*p);
        //auto a = Ref!(int)(s.x);
        writeln(a); //displays 1234
        s.x += 1;
        writeln(a); //displays 1235
        a += 1;
        writeln(s.x); //displays 1236
     }

     struct Ref(T)
     {
       T* ptr;
       this(ref T x) { ptr = &x; }
       @property ref T var() { return *ptr; }
       alias var this;
     }
     ```

I see no way to avoid overhead, as I see no simpler simulation.



More information about the Digitalmars-d-learn mailing list