What on earth is a ref function?

BCS none at anon.com
Sun Aug 8 15:43:50 PDT 2010


Hello simendsjo,

> The spec is very short here, and the example doesn't give me much..
> 
> // I thought "allows functinos to return by reference" meant it could
> return local variables..
> ref int* ptr() {
> auto p = new int;
> *p = 12;
> return p; // Error: escaping local variable
> }
> // So whats the difference between these functions?
> 

Just guessing but I'd guess that acts much like C++'s ref:

int*& Fn() { ... } // return a reference to a pointer to an int.

> ref int val() {
> auto p = new int;
> assert(*p == 0);
> *p = 10;
> assert(*p == 10);
> return *p;
> }

Return a reference to an int (that is also pointed to by a local variable) 
who's value is 10

> int val2() {
> auto p = new int;
> *p = 10;
> return *p;
> }

Return the value (10) of an int that is pointed to by a local variable.

> unittest
> {
> assert(val() == 10);
> assert(val2() == 10);
> auto retvalue = val() = 99; // References can be lvalues.. What?

The main point of references is that they can be lvalues.

> assert(retvalue == 99);
> }
-- 
... <IXOYE><





More information about the Digitalmars-d-learn mailing list