79537596

Date: 2025-03-27 01:03:20
Score: 1
Natty:
Report link

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?

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 like A tmp(10); f(tmp); instead of call to f(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 error error: 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.

Reasons:
  • RegEx Blacklisted phrase (2.5): Can someone explain
  • RegEx Blacklisted phrase (1): I get the error
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • High reputation (-2):
Posted by: Remy Lebeau