I have the following snippet:
#include <string>
int main(int argc, char *argv[])
{
std::string a, b, c;
a + b = c;
return 0;
}
Why doesn't this C++ code give compile-time error? This is probably because of the way std::string::operator+
has been implemented but then my question is: why was it implemented this way? In what cases is such behaviour needed?
You can assign to temporary objects. There is no rule preventing this.
If you don't want a member function to be invoked on a temporary (on an r-value, more generally), you can use a ref-qualifier in the function declaration.
But as you can see here, std::string::operator=
does not have a ref-qualified version.
I don't think that the Standard Committee allowed this behavior with a definite goal in mind; I guess the rationale behind this choice is to impose to the programmer the less rules as possible and let him to find a useful application, if any can exists.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With