Search code examples
c++referencelvalueampersand

Correct way to use reference lvalues


My code is the following:

void parentheses (int n, string& str, int left, int right){

    ... irrelevant... 

}
void solve(int n){
    parentheses(n,"",0,0);
}

However, this will give me an error, telling me that cannot bind non-const lvalue reference of type std::__cxx11::string& ... to an rvalue of type ‘std::__cxx11::string. In this case, if I still want to pass the string in as a reference, how should I modify my functions? I don't want to make them const because I want to functions to modify the original string, and I want them to be & precisely because I want to edit their values.


Solution

  • The function parentheses expects an lvalue in the std::string parameter, i.e. a named variable. However, you have supplied an rvalue (temporary) in this call:

    parentheses(n,"",0,0);

    An empty string object is created and passed to parentheses. You can avoid this problem by changing the definition of parentheses like so:

    void parentheses (int n, const string& str, int left, int right)
    

    Here str will bind to an rvalue/temporary, but you won't be able to change its value in the function. However, if you want to change the value of str you have to define a string variable and pass that to the function.

    Example:

    void solve(int n){
        std::string str;
        parentheses(n,str,0,0);
    }
    

    Note: no need to assign str to "" as a string is empty by default.