Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: cannot bind non-const lvalue reference of type ‘int&’ to an rvalue of type ‘int’

I need to create a Bar object, which has a private object Foo f.

However, the value of Foo object parameter should be passed by the specific method int genValue().

If I initialize f in the constructor scope Bar(){...}, the compiler yell error, something like there is no constructor Foo().

If I construct like this Bar(): f(genValue()), the compiler yells the error:

test.cpp: In constructor ‘Bar::Bar()’:
test.cpp:16:19: error: cannot bind non-const lvalue reference of type ‘int&’ to an rvalue of type ‘int’
 Bar(): f(genValue()){    
            ~~~~~~~~^~
test.cpp:7:2: note:   initializing argument 1 of ‘Foo::Foo(int&)’    
 Foo(int &x) {    
 ^~~

Example code:

class Foo {
public:
    Foo(int &x) {
        this->x = x;
    }
private:
    int x;
};

class Bar {
public:
    Bar(): f(genValue()){
    }
private:
    Foo f;

    int genValue(){
        int x;
        // do something ...
        x = 1;
        return x;
    }
};

int main() {

    Bar bar ();

    return 0;
}

How can I fix the problem, if I don't want to modify Foo class and its argument value should be passed from genValue()? And, I don't want to use pure pointer (*), but a solution with smart pointer is okay!

like image 797
sheucm Avatar asked Jan 04 '19 04:01

sheucm


People also ask

What does const reference mean in C++?

Constant References. A constant reference is really a reference to a constant. The use of const in a declaration of a reference (argument) means that we do not want to change the referenced object. "An initializer for const T& does not need to be an lvalue, or even of type T" The C++ Prog.

What is lvalue reference?

“l-value” refers to a memory location that identifies an object. “r-value” refers to the data value that is stored at some address in memory. References in C++ are nothing but the alternative to the already existing variable. They are declared using the '&' before the name of the variable.

Can lvalue bind to rvalue reference?

An lvalue reference can bind to an lvalue, but not to an rvalue.

Can Rvalue be const?

So an rvalue can be used both with rvalue overloads and a const lvalue reference.


1 Answers

Don't pass int&, it can't be bound to a constant or temporary because those can't be modified - use const int& instead.

Actually for simple types you should prefer to pass by value instead, and let the optimizer worry about providing the best implementation.

like image 62
Mark Ransom Avatar answered Oct 19 '22 02:10

Mark Ransom