refInt = ref int: how to achieve this? or is this a bug?

Ali Çehreli acehreli at yahoo.com
Wed Jun 17 21:01:53 UTC 2020


On 6/17/20 1:38 PM, mw wrote:

> alias refInt = ref int;


(Aside: I think this thread should be on the 'learn' forum.)

I've just come up with the following struct just to compile the code. It 
works but as you see with need for refInt(i) inside main, constructors 
are not called automatically in D. (Hence your thread. :) )

import std.stdio;

struct refInt {
   int * p;

   this(ref int i) {
     this.p = &i;
   }

   ref int reference() {
     return *p;
   }

   alias reference this;

   auto opAssign(int i) {
     reference() = i;
     return this;
   }
}

void f(refInt i) {
   i = 456;
}

void main() {
   int i = 123;
   writeln(i);
   f(refInt(i));
   writeln(i);
}

Ali


More information about the Digitalmars-d mailing list