What on earth is a ref function?

Simen kjaeraas simen.kjaras at gmail.com
Mon Aug 9 08:22:10 PDT 2010


simendsjo <simen.endsjo at pandavre.com> wrote:

> 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
> }

This fails because p itself is stack allocated. By reference means it
returns a hidden pointer to something. Because this is a pointer, you
can get the address of the returned value, and do things to it.


> // So whats the difference between these functions?
>
> ref int val() {
> 	auto p = new int;
> 	assert(*p == 0);
> 	*p = 10;
> 	assert(*p == 10);
> 	return *p;
> }

This returns what is in effect p - a pointer (reference) to an int.


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

This returns simply the value of *p.

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

Giving an example of what one can do with a reference:

ref int foo( ref int val ) {
     return ++value;
}

int n = 3;
foo( n ) = 4;
assert( n == 4 );
assert( foo( n ) == 5 );

-- 
Simen


More information about the Digitalmars-d-learn mailing list