First Draft: ref For Variable Declarations

Walter Bright newshound2 at digitalmars.com
Sun Apr 14 23:28:07 UTC 2024


I appreciate your thoughts.

I agree that ref parameters make it slightly less clear what is happening at the 
call site. But we don't really put documentation at the call site, we put the 
documentation at the callee. A ref parameter self-documents restrictions on how 
the pointer is used. `out` goes even further, it says that a value is not being 
passed in, only out. Pointers come with other behaviors - they can be 
incremented, and they can be free'd.

In my years of experience, I see a lot of operating system APIs that use a 
pointer. It's often unclear what is going to happen with that pointer. Most of 
the time, they stick to ref semantics, but not always. Like a char* being 
actually a string in C, rather than a reference to a char.

Just recently, I submitted a PR to replace some pointers in the DMD source code 
with refs, like this one:

https://github.com/dlang/dmd/pull/16379/files#diff-d58f278dd62016ccc4d0723aab00357f640541f027b68df715511d8e36c8115dR1773

Note how much simpler the line becomes, though it does exactly the same thing.

I've come to appreciate this difference.

And the more that arrays and refs can replace raw pointer use, the more memory 
safe the code is. Ref also makes it easy to switch a parameter from value <=> 
ref, for trying out which is faster.

It's worthwhile to extend the ability to use refs instead of pointers.

BTW, although Go has pointers, it does not allow pointer arithmetic. That makes 
them much like D's ref types.


More information about the dip.development mailing list