endless loop with ref and non-ref parameter

Ali Çehreli acehreli at yahoo.com
Thu Jan 24 17:13:36 PST 2013


On 01/24/2013 12:25 PM, Era Scarecrow wrote:

 >> What is also considered in function selection is the rvalue-lvalue
 >> distinction, which shouldn't affect the outcome here either.
 >
 > In case David's explanation was too confusing, then let's look at it. If
 > your variable is non-const, it will always select a non-const matching
 > one first. If there is no matching non-const, it converts it to const,
 > then tries again.
 >
 > void foo(A a) {
 > writeln("without ref");
 > //a is an lvalue but not const
 > //Foo(A) matches closer. Infinite loop

And that's exactly why this issue is so confusing.

Normally, const vs. immutable parameters are different in the way that 
they accept arguments:

- immutable is "limiting" because it insists that the argument is immutable.

- const is "welcoming" because it accepts mutable, const, and immutable.

However, according to your example and explanation above, in this case 
const is not welcoming but limiting! What the example shows is that, 
because the following function takes 'const ref A', now it "wants" 
'const A' but not 'A'. See, how in this case 'const' is not welcoming?

That is the problem in this whole confusing situation.

If there is another explanation that would bring sanity to the way I see 
things, I would love to hear about it. Does my understanging above 
regarding "limiting" vs. "welcoming" off? Perhaps that's where I go wrong?

 > foo(a);
 > }
 >
 > void foo(const ref A a) {
 > writeln("with ref");
 > }
 >
 > void foo2(A a) {
 > writeln("foo2 - without ref");
 > //const lvalue, foo(const ref A) is closer
 > foo(cast(const A) a)
 >
 > //rvalue, postblit call foo(A) (if it can)
 > foo(cast(const A) A());
 > }

Ali



More information about the Digitalmars-d-learn mailing list