Let’s consider that snippet, and please suppose that a, b, c and d are non-empty strings.
std::string a, b, c, d;
d = a + b + c;
When computing the sum of those 3 std::string
instances, the standard library implementations create a first temporary std::string
object, copy in its internal buffer the concatenated buffers of a
and b
, then perform the same operations between the temporary string and the c
.
A fellow programmer was stressing that instead of this behaviour, operator+(std::string, std::string)
could be defined to return a std::string_helper
.
This object’s very role would be to defer the actual concatenations to the moment where it’s casted into a std::string
. Obviously, operator+(std::string_helper, std::string)
would be defined to return the same helper, which would "keep in mind" the fact that it has an additional concatenation to carry out.
Such a behavior would save the CPU cost of creating n-1 temporary objects, allocating their buffer, copying them, etc. So my question is: why doesn’t it already work like that ?I can’t think of any drawback or limitation.