Why doesn't std :: basic_string support concatenation through expression patterns?

Qt QString can be combined with operator% , which uses expression patterns to pre-calculate the resulting string size and optimize multiple chain calls on operator+ . See this my question for more information.

Why didn't std::basic_string adapt a similar construct? Is this even valid for C ++ 11? I see only advantages and, obviously, compatibility with ABI can be violated by library developers when they want (and C ++ 11 served as a good reason even for libstdC ++).

+4
source share
2 answers

Because no one offered it for a standard; if someone does not offer anything, he does not fall. Also because it can break existing code (if they use operator+ ).

In addition, expression patterns do not work well in the presence of auto . Doing something simple like auto concat = str1 % str2; can be easily broken. Hope this is a problem that C ++ 17 will solve with some tools.

+4
source

In C ++ 11, std::basic_string supports move semantics, which means that you can optimize the concatenation of a number of lines with operator+ by allocating memory for the first line in the series, and then just building the remaining lines in the memory of the first line in the series, significantly reducing the number of memory allocations and copies needed to concatenate and return a series of lines.

I'm sure there are further optimizations that you can perform, as you pointed out using the Qt method, but the semantics of move allowed by C ++ 11 overcome the huge performance barriers that existed in the C ++ 03 version of std::basic_string , especially when combining a large number of lines together.

So for example, something like

 std::string a = std::string("Blah blah") + " Blah Blah " + " Yadda, Yadda"; 

can be done by allocating memory for the first line, and then using the semantics of movement, to "steal" the remaining memory from the first line to build the second or two lines in place, and only reallocate the memory at startup from extra space. Finally, the assignment operator can, using move-semantics, β€œsteal” the memory from the temporary value r created on the right side of the assignment operator, preventing a copy of the concatenated string.

+1
source

All Articles