Domanda

Qt's QStrings can be concatenated by operator% which uses expression templates to precalculate the resulting string's size and optimize several chained calls to operator+. See this question of mine for more info.

Why hasn't std::basic_string adapted a similar construct? Is this even allowed per C++11? I see only advantages and clearly ABI compatibility can be broken by library implementors when they want to (and C++11 provided a good reason even for libstdc++).

È stato utile?

Soluzione

Because nobody proposed it for the standard; unless someone proposes something, it doesn't get in. Also because it could break existing code (if they use operator+ that is).

Also, expression templates don't work well in the presence of auto. Doing something as simple as auto concat = str1 % str2; can easily be broken. Hopefully, this is an issue that C++17 will resolve via some means.

Altri suggerimenti

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top