I'm trying to figure out how C++ actually breaks down the argument-passing when the formal argument is a reference and the actual argument is of a type that requires type-conversion.
- Here's an example. Are the calls to
f(10)andg(5)supposed to compile/run or they supposed to throw an error?
f(10) passes an int but the formal-argument is a reference to const. So the compiler has to bind the reference to 10. How does it do that? What assignment statement does it create to bind it? would it create a temporary object (say tmp) and insert a statement like A tmp(10); f(tmp); instead of call to f(10)?
class A {
public:
A(int);
~A() = default;
};
void f(const A&);
void g(A&);
f(10);
g(5);
Can someone elaborate on what type-conversion and argument-passing rules apply here?
When running
g(5)call I get the error:error: cannot bind non-const lvalue reference of type ‘A&’ to an rvalue of type ‘A’
Can someone explain the reasoning behind this?
Acan be constructed from aintit can make the call tof(10)by converting the integer to an instance ofAand then pass that temporaryAbyconstreference to the function. Callingg(5)doesn't work since you can't pass a temporaryAby non-constreference.f(10)tof(A{10}). It's not quite the same, since the latter could do an implicit conversion fromAto something else, but it's close enough.f(const A&)and pass aA(5)to it)? Why do you keep talking about the non-existent and unrelated "assignment" or "statement"? The "reference initialization" page on cppreference may help. Also for C++17 and later, read about temporary materialization.