Cannot Bind Non-Const Lvalue Reference to Rvalue: A Resolution
The given code snippet encountered an error while initializing an object of class Foo within the constructor of class Bar. The error message indicates that a non-const lvalue reference (Foo f) is being bound to an rvalue (the result of calling genValue()).
In C , non-const reference parameters can only refer to named variables (lvalues). However, the result of genValue() is a temporary value (rvalue). To resolve this issue, we need to pass the value of genValue() by value (int).
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;
}
};
By changing the constructor argument to int, we can now initialize the Foo object within the constructor scope without any errors.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3