string s = "hello";
s + s = s; //compiles with no error/warnings
I was expecting a compilation error given rvalues are temporary values and can't be appear as an assigned value in an expression.
string s = "hello";
s + s = s; //compiles with no error/warnings
I was expecting a compilation error given rvalues are temporary values and can't be appear as an assigned value in an expression.
std::string
is a class type and so =
resolves to a normal member function call, i.e. (s + s).operator=(s)
.
You wouldn't expect member function calls on rvalues to fail generally and only since C++11 is there syntax to restrict member functions to lvalue arguments to the implicit object parameters.
For backwards-compatibility std::string::operator=
was of course not modified to be restricted to lvalues and even for new library additions it is very uncommon to restrict operator=
to lvalues. There isn't really much harm in allowing rvalues and it is occasionally useful, for example:
std::string a;
//...
std::string() = std::move(a);
This is supposed to "encourage" the temporary std::string
to take the memory resources from the moved-from a
and then release them when it is destroyed at the end of the expression. (Although std::string().swap(a)
would be be a better choice in this case.)
Ultimately the answer is simply because the language designers at the time decided it that way.
I was expecting a compilation error given rvalues are temporary values and can't be appear as an assigned value in an expression.
This is simply wrong. Thinking of rvalue/lvalue as what can be on the left-hand side of a =
is way too simplistic and at best applies only to non-class types.