phobos by ref or by value

Jonathan M Davis jmdavisProg at gmx.com
Sun Dec 16 22:19:50 PST 2012


On Monday, December 17, 2012 04:06:52 Dan wrote:
> > They'll use ref when it's required for
> > the semantics of what they're doing, but auto ref on function
> > parameters is
> > rare.
> 
> When would ref be required for semantics? I am asking this to
> learn the D way - so any guidelines are helpful. We have language
> spec and TDPL. Maybe we need another book or three in the vein of
> Meyers "50 Effective Ways".

ref is required when you want the argument you're passing in to be altered 
rather than the copy being altered. That's the same as in C++.

Ranges in general don't do deep copies when they're passed around for 
basically the same reasons that pointers don't. If you want to know more about 
ranges, this is probably the best resource at this point:

http://ddili.org/ders/d.en/ranges.html

There are probably plenty of cases in D where the equivalent of C++'s const& 
would be desirable, but D doesn't really have that at this point. The closest 
is auto ref, which only works with templated functions, and it doesn't prevent 
the argument from being mutated (though auto ref const would). Also, const in 
D is far more restrictive than it is in C++, making it so that forcing const 
on function parameters can be highly restrictive and annoying. It's an ongoing 
debate on how to solve that, as emulating C++'s const& and having const ref 
take rvalues has been rejected. So, in most cases, the issue is completely 
ignored at this point in Phobos. And since most functions in Phobos take 
either ranges or built-in types (where passing by value is not a problem), so 
in most cases, it's not an issue at all. Long term, it's something that should 
probably be addressed, but until the const ref situation is sorted out, it 
probably won't be.

Functions which take the element of a range rather than a range probably 
should do something to avoid unnecessary copies, and auto ref may be the 
solution to that at the moment, but it's not clear how that's going to be 
sorted out in the long run.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list