endless loop with ref and non-ref parameter

Jonathan M Davis jmdavisProg at gmx.com
Thu Jan 24 12:53:50 PST 2013


On Thursday, January 24, 2013 12:06:33 Ali Çehreli wrote:
> On 01/24/2013 11:33 AM, Jonathan M Davis wrote:
> > It's intended. constness matters more than refness when selecting a
> 
> function
> 
> > overload. From the docs ( http://dlang.org/function.html#<u>function</u>-
> > overloading ):
> > 
> > -----
> > Functions are overloaded based on how well the arguments to a function
> > can match up with the parameters. The function with the best match is se
> > lected. The levels of matching are:
> > 
> > no match
> > match with implicit conversions
> > match with conversion to const
> > exact match
> > -----
> 
> That doesn't explain why the first case selects the ref function:
> 
> void foo(A a) {
> writeln("without ref");
> foo(a); // <-- why is this foo(ref A)?
> }
> 
> void foo(ref A a) {
> writeln("with ref");
> }
> 
> foo(A) is the exact match there because the type of a is A.
> 
> What is also considered in function selection is the rvalue-lvalue
> distinction, which shouldn't affect the outcome here either.

Whether an argument is an lvalue or rvalue is very important to the issue. 
That's _exactly_ why the ref overload gets called in the first case. If the 
argument is an lvalue, the ref overload is selected. If the argument is an 
rvalue, the non-ref overload is selected. const only enters into it _after_ 
that.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list