Search code examples
c++stdpass-by-referencelvaluereference-binding

invalid initialization of non-const reference of type ‘std::string&


I am trying to trim string by using function rtrim() from string header in c++ without using algorithm.
What I did was I examine start and end position by if there is space exist, simply delete it out using isspace() but when I compile, now i get this error:

invalid initialization of non-const reference of type ‘std::string& {aka std::basic_string&}’ from an rvalue of type ‘const char*’

and here is my Code:

#include <iostream>
#include <string>
using namespace std;

string rtrim(string& s) {
    size_t i;
    for(i = s.length() - 1; i != (size_t)-1; i--) {
        if(!(isspace(s[i]))){
            break;
        }
    }
    return s.substr(0, i + 1);
}

int main(){
    cout << "|" << rtrim("   hello world\t ") << "|" << endl;
}

whenever I set parameter such as string s = ( "hello world\t "); and run cout << rtrim(s) << endl; seems to be working but it doesn't work as above code. any suggestions?


Solution

  • The above code would create temporary object of std::string on the stack and pass it to the function as non-const reference. This is dangerous as the function could modify the object (which doesn't make sense) or remember the reference to the object and try modifying it out of its scope once the object is already destroyed.

    In your function you actually don't require non-const reference, so just change the parameter to const std::string &s and it will work.