Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why must use const reference when reference to literals

I know only object could have reference. But literals are not object. So I could understand why following code cannot compile:

int &a = '4';
int &b = 2;

However, when I add const in front of them, it could work!!

const int &a = '4';
const int &b = 2;

I do not know why. Could anyone help me?

like image 522
sydridgm Avatar asked Mar 21 '26 14:03

sydridgm


1 Answers

A integer or character literal is a prvalue [expr.prim.general]

A literal is a primary expression. Its type depends on its form (2.13). A string literal is an lvalue; all other literals are prvalues.

Since it is a prvalue we are allowed to take a const & to it but we cannot take a reference to it. If we take a const & to the temporary the the lifetime of the temporary will be extended to the point where the reference goes out of scope.

{
    const int & a = 42;
    //line of code
    //42 still exits here
} // a goes out of scope and now 42 is gone
like image 58
NathanOliver Avatar answered Mar 23 '26 04:03

NathanOliver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!