On Wednesday, 19 December 2018 at 19:58:53 UTC, Neia Neutuladh wrote:
On Wed, 19 Dec 2018 17:28:01 +0000, Vijay Nayar wrote:
Could you please elaborate a little bit more on this? In the linked program, I had expected that "ref" would return a reference to "a" that would behave similar to a pointer.

They work like pointers that automatically dereference when assigning to the base type.

Only three things in D can be ref:
* A function parameter
* A function return value
* A foreach variable (since that's either going to be a function return value, a function parameter, or a pointer, depending on what you're
iterating over)

So when the compiler sees something like:

    ref int foo();
    auto a = foo();

It sees that the type of 'a' has to be the same as the return type of 'foo'. Except that's not possible, so it uses the nearest equivalent type: int.

And if you have:

    ref int foo();
    int a = foo();

That obviously converts by copying the value.

To be fair even in c++ this won't be a reference.

int& foo();
auto a = foo(); // a == int
auto& a = foo(); // a == int&

So it shouldn't be that surprising.

Reply via email to