So what's the big - O analysis of that '+' operation? Where is this
documented? What if I want to sacrifice a bit of safety for speed, as we did
with C? Can I overload the string '+' operator to achieve this?
It is interesting to note, that you can implement + style string
concenation with c++ strings and templates _very_ efficiently.
Here's the input:
foo::string x = a + b + c;
For simplicity, I omit the foo namespace from this point forward. We
need to state what *we* think is the optimal result (well optimal is
that nothing is done but let's say, with minimum number of operations
which still achieve something, let's not consider lazy evaluation and
similiar for this exercise).
What would be, in my humble opinion, efficient would be in pseudo code:
allocate a.length() + b.length() + c.length() bytes of memory in x, and
copy the a, b and c into the x.
This is possible using the proposed syntax. We need to implement a
string expression class, which encapsulates the expresion which is
being assigned into a string object, in this case x.
a + b is when we look at the types: string + string, result type is
string. Here comes the twist, we implement operator + which instead
returns a new type, which only encapsulates the parameters of the +
operation.
The new type, let's call it, "expr" so the above becomes:
expr operator + (string,string)
The next + operator with rhv of c will be of form:
expr operator + (expr,string)
And last, the assignment to x will be of form:
expr operator = (expr)
(references et cetera omitted for clarity)
When we implement this with templates, the expr object will be a type,
encapsulating a lot of information about the expression on the right
side of the assignment.
At this stage, we can compute a sum of the type tree on the right
(using the length of the string objects), this works so that the expr
object sums both left and right arguments lengths - recursively.
Because this "recursion" is done at code generation time, the recursion
is flattened (we are assuming the c++ implementation isn't braindead,
it could be but that is another matter, then there are bigger things to
worry, I think).
Next thing the operator = does is, that it just concatenates the text
as it best sees fit. Whatever is "optimal", efficient whatever. It's
actually pretty trivial to write, too.