Why const int& allows r value reference | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why const int& allows r value reference

Hi We all know that int&& i = 12; is valid for c++11 as it is r value reference. And int& i = 12; is not valid as 12 is not lvalue. However, why const makes it valid i.e. const int& i = 12; is why valid statement?

9th May 2021, 12:19 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
4 Answers
+ 2
That's because how "const" works according to standards. When doing const int& i = 12; The value 12 is not directly bound to variable "i", instead 12 is first bound to a temporary int variable ( which was created behind the scenes ) with an lvalue. This is the variable to which your const variable binds to. If you want to see how exactly is this happening, then you can see the following program which generates a C like GIMPLE representation( Intermediate representation to which gcc's front end compiles your code to ) of your code. https://code.sololearn.com/cVlF0YdTz3L4/?ref=app
9th May 2021, 3:18 PM
Arsenic
Arsenic - avatar
+ 1
Hey Ketan Lalcheta 1.A reference may be bound only to an object, not to literal or to result of expression . 2.A non-const reference can be used to change the value of the variable it is referring to. Hence, C++ does not permit a non-const reference to a const variable. EX: int &var=4; we can change value of reference , but logically it is not possible to change 4 to any value.hence it is illegal ! const int &var =4 ; here 4 is used constant and also we are not changing the value so it is legal write constant ! HOPE THIS WILL HELP YOU !
9th May 2021, 1:29 PM
Giriraj Yalpalwar
Giriraj Yalpalwar - avatar
+ 1
Thanks Arsenic and Thirt13n ... It's useful information... However, I tried to get code by Arsenic but could not get it more. I got point that const is bound to some temporary variable ... Is it correct ? Refer below code but it does not call copy constructor : https://code.sololearn.com/c0xmFKfRS76I/?ref=app
9th May 2021, 4:06 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 1
Ketan Lalcheta When doing const test& t = test(); It gets converted into something like this :- test _1 = test() test const& t = _1; You can see that the second line is creating const "reference" to another variable with lvalue and not creating a copy of it thus copy constructor is not being called.
9th May 2021, 4:38 PM
Arsenic
Arsenic - avatar