gcc/clang "cannot bind non-const lvalue reference to an rvalue" in CI
A non-const lvalue reference can only bind to a modifiable, named object. A temporary (rvalue) cannot bind to it because modifications would be lost when the temporary dies.
What this error means
Passing a literal, a function result, or a constructed temporary to a parameter of type T& fails with "cannot bind non-const lvalue reference of type T& to an rvalue".
gcc
app.cpp:9:7: error: cannot bind non-const lvalue reference of type 'int&' to an rvalue of type 'int'
9 | inc(5);
| ^Common causes
How to fix it
Pass an lvalue or change the parameter
- Pass a named variable so a modifiable lvalue exists.
- If the function does not modify the argument, take const T& or T by value.
gcc
int x = 5; inc(x); // bind to a named lvalue
void inc(const int& n); // or take const ref if read-onlyHow to prevent it
- Take const T& or by-value parameters for read-only inputs, and pass named lvalues when a function must modify its argument.
Frequently asked questions
What causes ""cannot bind non-const lvalue reference""?
Passing a literal, a function result, or a constructed temporary to a parameter of type T& fails with "cannot bind non-const lvalue reference of type T& to an rvalue".
How do I fix "cannot bind non-const lvalue reference"?
Pass an lvalue or change the parameter
Related guides
gcc/clang "taking address of temporary" in CIFix gcc/clang "taking address of temporary" in CI - the address of a temporary or rvalue is taken, producing…
gcc/clang "passing const X as this discards qualifiers" in CIFix gcc/clang "passing 'const X' as 'this' argument discards qualifiers" in CI - a non-const member function…
gcc/clang "call to non-constexpr function" in constant expression in CIFix gcc/clang errors where a constant expression calls a non-constexpr function in CI - a constexpr context r…