Why can't we make reference variables?

Tommi tommitissari at hotmail.com
Wed Aug 29 16:44:16 PDT 2012


On Wednesday, 29 August 2012 at 21:37:33 UTC, Era Scarecrow wrote:
>  struct R {
>    ref int r;
>    this(ref int i) {r = i;}
>  }

I had totally forgotten what it says in "The book" about struct 
and class construction. It's basically that all fields are first 
initialized to either T.init or by using the field's initializer. 
That means the use of ref inside class or struct would be quite 
restricted:

int globalVal;

struct MyStruct
{
     // ref int defaultInitRef; // Illegal: reference variables
                                // can't be default initialized

     ref int explicitRef = globalVal; // Fine

     this(int val)
     {
         explicitRef = val; // Assigns val to globalVal (because
                            // explicitRef references globalVal)
     }
}


More information about the Digitalmars-d mailing list