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
I prefer this, adding a rvalue-reference version, that makes both reference and rvalue-reference arguments working.
yes, you have to define a variable and then call rtrim using it instead of temporary object.