Why can't we make reference variables?

Tommi tommitissari at hotmail.com
Wed Aug 29 19:53:54 PDT 2012


...although, now I'm thinking that having reference variables as 
members of struct or class won't ever work. And that's because 
T.init is a compile-time variable, and references can't be known 
at compile-time (unlike pointers, which can be null). Perhaps the 
easiest way to implement reference variables would be to just 
think about them as syntactic sugar, and use lowering. Something 
like this user code...

void main()
{
     int           var = 123;
     immutable int imm = 42;

     ref int rVar = var;
     rVar = 1234;

     ref immutable int rImm = imm;
     auto mult = rImm * rImm;
}

// ...would get lowered to:

void main()
{
     int           var = 123;
     immutable int imm = 42;

     int* pVar = &var;
     (*pVar) = 1234;

     immutable(int)* pImm = &imm;
     auto mult = (*pImm) * (*pImm);
}

And this kind of initialization would be always illegal:
ref int rVar;


More information about the Digitalmars-d mailing list