Home  >  Article  >  Backend Development  >  How to Resolve Binding Errors When Initializing Private Members with Non-Const Lvalue References?

How to Resolve Binding Errors When Initializing Private Members with Non-Const Lvalue References?

Barbara Streisand
Barbara StreisandOriginal
2024-10-30 01:46:02295browse

 How to Resolve Binding Errors When Initializing Private Members with Non-Const Lvalue References?

Resolving Binding Errors: Converting Lvalue References to Rvalues

When constructing objects with private members that require non-const lvalue references in their constructors, like in the case of Foo, it can be challenging to pass appropriate values. Modifying the Foo class is not always feasible, and using raw pointers is undesirable.

In this situation, the error stems from trying to bind an lvalue reference of type 'int&' to an rvalue of type 'int' when initializing the private member 'f' of the Bar class. The Foo constructor expects a named variable, not a temporary value, as in this case, where 'genValue()' returns an integer.

To address the issue, consider passing the argument to the Foo constructor by value instead of reference. By doing so, a copy of the integer returned by 'genValue()' is created and assigned to the 'x' member of the Foo object.

Here's the corrected code:

<code class="cpp">class Foo {
public:
    Foo(int x) { // Pass by value
        this->x = x;
    }
private:
    int x;
};

class Bar {
public:
    Bar(): f(genValue()) { // Pass by value
    }
private:
    Foo f;

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

By passing the genValue() return value as an actual argument, the compiler assigns the value of the temporary variable to the Foo object's x member. This approach avoids the error while maintaining the intended behavior.

The above is the detailed content of How to Resolve Binding Errors When Initializing Private Members with Non-Const Lvalue References?. 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