Home >Backend Development >C++ >Why Can\'t I Bind a Non-Const Lvalue Reference to an Rvalue in C ?

Why Can\'t I Bind a Non-Const Lvalue Reference to an Rvalue in C ?

DDD
DDDOriginal
2024-10-31 04:07:34370browse

 Why Can't I Bind a Non-Const Lvalue Reference to an Rvalue in C  ?

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

<code class="cpp">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;
    }
};</code>

By changing the constructor argument to int, we can now initialize the Foo object within the constructor scope without any errors.

The above is the detailed content of Why Can\'t I Bind a Non-Const Lvalue Reference to an Rvalue in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn