Pass by reference

Regan Heath regan at netmail.co.nz
Fri Jun 8 10:20:50 PDT 2007


Deewiant Wrote:
> Lionello Lunesu wrote:
> > Regan Heath wrote:
> >> As Don says; 'ref' is an alias of 'inout'.  It's ver y purpose is to
> >> indicate a variable which is going to be modified. Therefore it stands to
> >> reason that function parameters passed as 'ref' will be mutable by default.
> >> :)
> > 
> > Actually, it might be a nice distinction to keep both 'inout' and 'ref', 
> > where 'inout' would be mutable, but 'ref' not? 'ref' would then be an 
> > optimized version of 'in'.
> > 
> > Or will 'inout' disappear completely?
> > 
> 
> 'ref' meaning what C++'s 'const foo&' is how I originally understood it, but
> from all the discussion I've gathered that 'inout' will be deprecated and then
> phased out after all. So 'ref' will be only the new name for 'inout'.
> 
> I hope I'm wrong, I think 'inout' is more self-documenting than 'ref'.

I liked 'inout' better than 'ref' too.  I was against the initial proposal before I left for 6 months and when I got back, there it was!

'inout' was originally intended to signal the intent of the function to "read from the parameter and write back to it".  Much like 'out' just meant "I will only write to this" and the default 'in' meant "I will only read this".

'ref' however is an instruction to pass by reference, which is a whole other kettle of fish.  Yes, 'inout' has to pass by reference in order to carry out it's intention but that doesn't make it the same thing.

My original argument against adding anything more to the language was something along the lines of.. 

If you want to pass something by reference, why not pass a pointer to it.  After all, in D, you can dereference a pointer in exactly the same way as you would the thing itself, eg.

struct A { int member; }
void foo(A a) { a.member = 5; }
void foo(A* a) { a.member = 5; }

notice that to dereference a struct passed by value, or a pointer to a struct you always use '.'

That said, the call site would look like foo(&a); instead of the cleaner foo(a)... which is perhaps why C++ added a pass-by-reference & to be used in place of the pointer * syntax.

Hmm.. idea;  why not allow foo(a) and automatically convert to foo(&a) internally if 'a' is not a pointer.  I mean, the compiler knows what 'a' is, it knows what 'foo' wants, why can't we have the syntax automatically, much like we do for dereferencing.

Regan



More information about the Digitalmars-d mailing list