c++parametersliteralsrvaluepass-by-const-reference

Why is it allowed to pass rvalues by const reference but not by normal reference?


The following program

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

will work if called with a literal like this

display(5);

but without the const it won't work.

So how can a const reference keep pointing to an rvalue (temporary object)?


Solution

  • 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).