The expression "std :: string + char" creates another std :: string?

Does the expression below create another std :: string and then add it to s1?

std::string s1 = "abc", s2 = "xyz"; s1 += s2 + 'b'; 

If this prevents this situation (they will be added to s1 without additional work)?

  std::string s1 = "abc", s2 = "xyz"; s1 += s2; s1 += 'b'; 

Do these rules also match the expression "std :: string + std :: string"?

+5
source share
2 answers

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.

+4
source

It depends on the context. There will be no other object in your code snippet, s2 and 'b' will be added to the existing s1 .

http://www.cplusplus.com/reference/string/string/operator+=/

For example, in this case:

 std::string s1 = "abc"; std::string s2 = "zxy"; std::string result = s1 + s2; 

result is a new object concatenating s1 and s2

0
source

Source: https://habr.com/ru/post/1261964/


All Articles