skip to Main Content
inline string& rtirm(string& s)
{
    s.erase(s.find_last_not_of(' ') + 1);
    return s;
}

const char* buf = " abc ";
string s_trim = rtirm(string(buf));

This code has been working well until I upgraded visual studio to 2022 and with C++20.

Error C2664 ‘std::string &rtirm(std::string &)’: cannot convert
argument 1 from ‘std::string’ to ‘std::string &’

I clearly understand the reason — a reference can’t refer to a tempoary object.
But this make the code more complicated. Do I have to define a variable before calling rtirm?

string temp{buf};
string s_trim = rtirm(temp);

2

Answers


  1. Chosen as BEST ANSWER
    inline string& rtirm(string& s)
    {
        s.erase(s.find_last_not_of(' ') + 1);
        return s;
    }
    
    inline string rtrim(string&& s)
    {
        s.erase(s.find_last_not_of(' ') + 1);
        return s;
    }
    
    void test(){
        const char* buf = "    abc    ";
        string sTemp{ buf };
        rtrim(sTemp);
        
        string s_trim = rtrim(string(buf));
    }
    

    I prefer this, adding a rvalue-reference version, that makes both reference and rvalue-reference arguments working.


  2. yes, you have to define a variable and then call rtrim using it instead of temporary object.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search