Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't this std::string C++ code give compile-time error?

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?

like image 816
syntagma Avatar asked Mar 14 '23 00:03

syntagma


1 Answers

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.

like image 146
Paolo M Avatar answered Mar 17 '23 04:03

Paolo M