Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is const keyword necessary

My code does not compile.

int foobar()
{
    // code
    return 5;
}

int main()
{
   int &p = foobar(); // error
   // code

   const int& x = foobar(); //compiles
}

Why does adding the keyword const make the code compile?

like image 861
user6435212 Avatar asked Dec 07 '22 21:12

user6435212


2 Answers

In C++ temporaries cannot be bound to non-constant references.

In

 int &p = foobar(); 

The rvalue expression foobar() generates a temporary which cannot be bound to p because it is a non-const reference.

 const int &x = foobar();

Attaching the temporary to x which is a reference to const prolongs its lifetime. It is perfectly legal.

like image 123
Prasoon Saurav Avatar answered Dec 23 '22 10:12

Prasoon Saurav


Because foobar() is returning by value; this result is a temporary. You cannot have a non-constant reference of a temporary.

If this were not true, what would this code do?

int &x = foobar();

x = 1;  // Where are we writing to?
like image 39
Oliver Charlesworth Avatar answered Dec 23 '22 11:12

Oliver Charlesworth