Why is it allowed to pass R-Values by const reference but not by normal reference?

Mekacher Anis picture Mekacher Anis · Mar 19, 2016 · Viewed 10.3k times · Source

as the title says why is it allowed to pass R-Values(literals) by constant reference but not normal reference

void display(const int& a)
{
cout << a ;
}

will work if called display(5) but without the const it won't work ****** I mean how can a const reference keep pointing to an R-Value (anonymous variable) ******

Answer

Tanz87 picture Tanz87 · Mar 19, 2016

For your final question:

how can a const reference keep pointing to an R-Value (anonymous variable)

Here is the answer. The C++ language says that a local const reference prolongs the lifetime of temporary values until the end of the containing scope, but saving you the cost of a copy-construction (i.e. if you were to use an local variable instead).