Blog post: What D got wrong

Vijay Nayar madric at gmail.com
Wed Dec 19 17:28:01 UTC 2018


On Wednesday, 12 December 2018 at 07:44:12 UTC, Walter Bright 
wrote:
> On 12/11/2018 4:51 AM, Nicholas Wilson wrote:
>> > Returning a reference
>> Wow, thats f*ck'n stupid! https://run.dlang.io/is/SAplYw
>
> It's quite deliberate.
>
> ref in C++ is a type constructor, but it's so special-cased to 
> behave like a storage class, it might as well be one. In D it 
> is.
>
> (For example, ref in C++ can only appear at the top level. 
> There are no "pointers to refs".)
>
> refs exist so the lifetime of them can be controlled for memory 
> safety. Treating them as flexibly as pointers would make that 
> pretty difficult. refs are the primary way a memory safe 
> container can expose pointers to its contents.

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. But when 
that reference is assigned to "b", and "b" is modified, "a" 
appears to retain its original value, implying that "b" is a copy.

When was the copy of "a" made?  Was it during the assignment to 
"b"?

I use ref regularly, especially when I have to port C++ code that 
does exactly that, exposing modifiable references to its members. 
And in my experience it works quite well, especially for array 
types and classes.

So what is the best way to understand this program and know why a 
copy of "a" is made?


More information about the Digitalmars-d-announce mailing list