Why is this code well-formed? I'm not passing a reference to the function:
void function(const int& ref) {
}
int main()
{
function(1);
}
Constant lvalue references can bind to rvalues. Rvalues, like your literal 1
, don't have a persistent alias, so if you were to modifying it, you wouldn't be able to observe the effect, but if you promise not to modify it (namely by accessing it through a constant reference), you can still have perfectly sensible code, and that's why this binding is allowed.
(You can also bind rvalues to (mutable) rvalue references: void function(int &&)
In that case, the rvalue reference becomes the (unique) alias of the value.)
Note also that without this rule it would be impossible to initialize variables from functions that return prvalues, or use copy-initialization at all:
struct T { T(int); };
T f();
T x = 1; // === "T x = T(1);", copy constructor wants to bind to prvalue
T x = f(); // ditto
T x((f())); // ditto
The compiler can create a temporary from the constant and temporaries are allowed to bind to const references. If the reference wasn't const, this wouldn't be allowed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With