In C++11 std::basic_string
supports move semantics, meaning that you can optimize the concatenation of a series of strings using operator+
by allocating memory for the first string in the series, and then simply constructs the rest of strings in the memory of the first string in the series, vastly reducing the number of memory allocations and copys necessary to concatenate and return a series of strings.
I'm sure there are further optimizations that can be done as you have pointed out with Qt's method, but the move-semantics allowed by C++11 overcomes a huge hurdle in performance that existed in the C++03 version of std::basic_string
, especially when concatenating a lot of strings together.
So for instance, something like
std::string a = std::string("Blah blah") + " Blah Blah " + " Yadda, Yadda";
can be done by allocating memory for the first string, and then using move semantics, "steal" the remaining memory from the first string to construct the second-two strings in-place, and only re-allocate memory when you run out of extra space. Finally, the assignment operator can, using move-semantics "steal" the memory from the temporary r-value created on the right-hand side of the assignment operator, preventing a copy of the concatenated string.