Pass by reference
Regan Heath
regan at netmail.co.nz
Fri Jun 8 15:01:51 PDT 2007
Bill Baxter Wrote:
> Regan Heath wrote:
> > Deewiant Wrote:
> >> Lionello Lunesu wrote:
> > 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.
>
> Good idea. I'd be perfectly happy to do that with structs. Now that
> you mention it, it is kind of inconsistent that D basically turns
> astruct.foo into (&astruct).foo for you, but it wont turn foo(astruct)
> into foo(&astruct) for you. (Here assuming the D meaning of '.' is like
> C++ '->')
>
> But how do you handle overloads on '*'?
> void foo(int x) { /* sets foo to x */ }
> void foo(int* x) { /* returns foo via x*/ }
>
> I guess that's already impossible with inout anyway. We get along
> currently just fine without being able to overload on inout, so maybe
> the loss of overload on '*' would go mostly unnoticed?
>
> I think this feature should be limited to one level, though.
> Calling a 'void foo(int **x)' with a plain int is probably not going to
> do what the user expects.
True, but calling with an int* should be allowed? I'm wondering if that would be ok or just confusing... not sure.
Regan
More information about the Digitalmars-d
mailing list