f(10)
passes anint
but the formal-argument is a reference toconst
. So the compiler has to bind the reference to 10. How does it do that? What assignment statement does it create to bind it?
It can't bind to 10
directly. It can only bind to an A
object.
would it create a temporary object (say
tmp
) and insert a statement likeA tmp(10); f(tmp);
instead of call tof(10)
?
Essentially, yes. A const reference can bind to a temporary, so that is exactly what the compiler does - it implicitly creates an unnamed temporary A
object, constructed using 10
as input to its constructor, and then destroys that object after the end of the full statement (ie the ;
) is reached.
When running
g(5)
call I get the errorerror: cannot bind non-const lvalue reference of type ‘A&’ to an rvalue of type ‘A’
. Can someone explain the reasoning behind this?
It is because a non-const reference is not allowed to bind to a temporary, so you will have to create a non-temporary A
object yourself.