Smart references

Zach the Mystic via Digitalmars-d digitalmars-d at
Fri Mar 13 08:21:41 PDT 2015

On Wednesday, 11 March 2015 at 20:33:07 UTC, Andrei Alexandrescu 
> I'm investigating D's ability to define and use smart 
> references. Per the skeleton at 
>, lines:
> #6: You can't default-initialize a ref.
> #7: You can't copy a ref - copying should mean copying the 
> object itself.
> #9: Per this example I'm hooking a reference with an Owner. The 
> reference hooks calls to opAddRef and opRelease in the owner.
> #23: Assigning the reference really assigns the referred.
> #28: A reference is a subtype of ref T. Most operations against 
> the reference will be automatically forwarded to the underlying 
> object, by reference ("ref" is important here).
> As unittests show, things work quite nicely. There are a few 
> things that don't:
> #70: Attempting to copy a reference fails on account of the 
> disabled postblit. There should be a way to tell the compiler 
> to automatically invoke alias this and create a copy of that 
> guy.
> #81: Moving from a reference works by moving the Ref object. 
> There should be a way to tell the compiler that moving should 
> really move the payload around.
> There are a couple other issues not represented in the 
> unittest, for example related to template deduction. In a 
> perfect world, Ref would masquerade (aside from having a 
> different layout, ctor, and dtor) as an lvalue of type T.
> But in fact I think solving the matters above would go a long 
> way toward making smart references nicely usable. Although my 
> example is centered on reference counting an owner, there are 
> other uses of smart references. Are all these worth changing 
> the language?

Are the suggested changes also related to the possibility of 
making `ref` a type?

I have no opposition in principle to expanding struct semantics 
to be as transparent as possible. But then I ask, what prevented 
them from being expanded until now? From reading these forums, 
I've learned that C++ reference types have a lot of problems. 
Does expanding the semantics of structs run the risk of 
encountering same sorts of problems C++ references have?

The ideal is to find a way to add semantics without adding 
ambiguity (i.e. to make sure both the compiler and the programmer 
always choose the right interpretation of a given construct). So, 
for example, if you pass a `Ref!X` type to a type `X` parameter, 
or you pass an `X` type to a `Ref!X` parameter, the result is 
easy for both the compiler and the human to figure out. That's 
all I've got.

More information about the Digitalmars-d mailing list