You are correct that each concatenation could require an allocation. Consider an expression like this, where each variable is a string:
a = b + c + d + e;
This requires three concatenation operations and three temporaries, each of which requires a new allocation.
A simple solution is to use std::ostringstream
, which should not require as many reallocations:
std::ostringstream ss;
ss << b << c << d << e;
a = ss.str();
However, if we are concatenating only strings, we can do one better, and allocate exactly the right size of string (C++11-compatible implementation):
std::size_t total_string_size()
{
return 1;
}
template <typename... T>
std::size_t total_string_size(std::string const &s, T const & ...tail)
{
return s.size() + total_string_size(tail...);
}
void concat_strings_impl(std::string &) { }
template <typename... T>
void concat_strings_impl(std::string &out, std::string const &s, T const & ...tail)
{
out += s;
concat_strings_impl(out, tail...);
}
template <typename... T>
void concat_strings(std::string &out, T const & ...strings)
{
out.clear();
out.reserve(total_string_size(strings...));
concat_strings_impl(out, strings...);
}
Now we can call concat_strings(a, b, c, d, e)
to perform the equivalent of a = b + c + d + e;
in a single reallocation. (Demo)
operator +
like:auto foo = string1 + string2 + "some text" + string3;