All overloaded + operators containing std::string return a new std::string object. This is the inevitable conclusion that you will achieve when you finally decrypt the relevant documentation .
Thus, in the first example of your question, the + operator will return a temporary object that will be destroyed when the next operation += completed immediately.
Having said that: the C ++ compiler is allowed to use any optimization that gives identical observable results. It is possible that the C ++ compiler can understand that you can avoid the need to create a temporary object by substantially changing the first version of the code to the second. I do not think this is very likely, but it is possible. There are no noticeable differences in the results between the two versions of the code, so optimization is fair play.
But technically, the + operation creates a temporary std::string object.
source share