Blog post: What D got wrong
Steven Schveighoffer
schveiguy at gmail.com
Thu Dec 20 15:13:51 UTC 2018
On 12/19/18 2:58 PM, 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.
I would say it a little bit differently -- the return *type* of foo is
int. In D, ref is not part of the type at all.
For example, even when it *could* use ref, it doesn't:
int x;
ref int foo() { return x; }
void bar(Args...)(Args args)
{
pragma(msg, __traits(isRef, args[0]));
}
bar(foo()); // outputs false at compile time
The storage class is completely separate from the type. Which is
different from C++, where it's like a storage class but is really a type
constructor, hence Walter's post.
-Steve
More information about the Digitalmars-d-announce
mailing list