Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending the lifetime of a temporary value in C++

const int &ra=3;
  1. As I know, making ra const will extends the lifetime of the temporary r-value which is in this case 3. This is a little bit confusing, as I know ra should have the same address as r-value which is here 3, but 3 is not a real variable and it does not have a memory where it's stored. So how can this be possible?

  2. what is the difference between:

    const int& ra=a;
    

    and

    int& const ra=a;
    
like image 992
AlexDan Avatar asked Nov 30 '22 15:11

AlexDan


1 Answers

but 3 is not a real variable and it does not have a memory where it's stored. so how can this be possible ?

Actually a temporary object gets created out of the literal 3, and then that temporary is bound to the const reference. That is how it becomes possible.


Now your next question: the difference between these two

const int& ra=a;
int& const ra=a;

is that the second statement is illegal.

like image 88
Nawaz Avatar answered Dec 14 '22 07:12

Nawaz