Wrong inspection - expression must be rvalue
I'm using quite a lot of list in my app and see a wrong inspection which flags as an error. Below a short code snippet to explain it.
In the first while loop the code shall copy the returned reference to a string variable. Actually the compiled code is OK and works, however CLion flags it with expression must be rvalue which is wrong. C++ in this case copies the value from the referenced item to the variable, thus no warning necessary. I checked the known issues, however not found this case (maybe hidden in the two other issues that deal with rvalue).
In the second while loop I use a reference, the inspection error message is gone, however the code does not work anymore. The pop_front() removes the string from the list and thus the reference is gone. This is a simplified example, the real loop is more complex :-) .
As an interesting experiment: enable the string name; on top of the first while loop (remove the //) and then the wrong inspection is also gone :-) . Well, in this case I have the warning that a local variable hides a variable in an upper scope and this is obviously OK.
Code snippet:
shared_ptr<list<string> > func1() {
shared_ptr<list<string> > lst = make_shared<list<string> >();
string tst("testing-1");
lst->push_back(tst);
tst = "testing-2";
lst->push_back(tst);
return lst;
}
int main() {
shared_ptr<list<string> > names = func1();
size_t size = names->size();
cout << "List size - 1 : " << size << endl;
// string name;
while (!names->empty()) {
string name = names->front(); // expression must be rvalue
names->pop_front();
cout << "name (1): " << name << endl;
}
names = func1();
size = names->size();
cout << "List size - 2 : " << size << endl;
while (!names->empty()) {
const string& name = names->front(); // OK, however can't use 'name' anymore after pop_front
names->pop_front();
cout << "name (2): " << name << endl;
}
return 0;
}
请先登录再写评论。
We have a related issue in the tracker already: https://youtrack.jetbrains.com/issue/CPP-7473. Please comment or upvote. Sorry for the inconvenience!