In case that somehow you think of StringBuilder in mananged realms.
You can use Alphabet (Google) Library, ABCLib, ABCL or just Abseil.
Abseil's Strings library look ahead and allocate all it need at once, then build string in it like you want. For concat job, you just need absl::StrCat() and absl::StrAppend().
I'm not any good at explaining things. Perhaps this godbolt link below may speak better than I do.
godbolt.org/g/V45pXJ
Learn more on YouTube : CppCon 2017: Titus Winters “Hands-On With Abseil” (ffw to 32min)
youtube.com/watch?v=xu7q8dGvuwk&t=32m
#include <string>
#include <iostream>
#include <absl/strings/str_cat.h>
int main()
{
std::string s1,s2,s3,s4,
s5,s6,s7,s8,
s9,s10,s11,s12;
std::getline(std::cin, s1);
std::getline(std::cin, s2);
std::getline(std::cin, s3);
std::getline(std::cin, s4);
std::getline(std::cin, s5);
std::getline(std::cin, s6);
std::getline(std::cin, s7);
std::getline(std::cin, s8);
std::getline(std::cin, s9);
std::getline(std::cin, s10);
std::getline(std::cin, s11);
std::getline(std::cin, s12);
std::string s = s1 + s2 + s3 + s4 + // a call to operator+ for each +
s5 + s6 + s7 + s8 +
s9 + s10 + s11 + s12;
// you shall see that
// a lot of destructors get called at this point
// because operator+ create temporaries
std::string abseil_s =
absl::StrCat(s1,s2,s3,s4, // load all handles into memory
s5,s6,s7,s8, // then make only one call!
s9,s10,s11,s12);
return s.size() + abseil_s.size();
// you shall see that
// only "real" s1 - s12 get destroyed
// at these point
// because there are no temporaries!
}
Update 2021
Today you can alternatively use fmt:format
or std::format
when the c++20
library implementation completed. (Current fmtlib
now bumps support into c++14.)
The format
will lookahead like in Abseil StrCat
, so no wasted temporaries.
string fmt_s =
fmt::format("{}{}{}{}{}{}{}{}{}{}{}{}",
s1,s2,s3,s4, // load all handles into memory
s5,s6,s7,s8, // then make only one call!
s9,s10,s11,s12);
[LIVE]