Suppose I have a row vector, and I want to combine them through std :: accumulate.
If I use the following code:
std::vector<std::string> foo{"foo","bar"}; string res=""; res=std::accumulate(foo.begin(),foo.end(),res, [](string &rs,string &arg){ return rs+arg; });
I am sure there will be a temporary construction of the object.
In this answer, they say that the effect of std :: accumulate is specified this way:
Computes its result by initializing the battery acc with the initial value init, and then changing it with acc = acc + * i or acc = binary_op (acc, * i) for each iterator i in the range [first, last] in order.
So, I am wondering how to do this in order to avoid the unnecessary construction of temporary objects.
One idea was to change lambda like this:
[](string &rs,string &arg){ rs+=arg; return rs; }
In this case, I thought I could force the string concatenation and help the compiler (I know that I shouldn't ) omit the unnecessary copy, as this should be equivalent (pseudo-code):
accum = [](& accum,& arg){ ...; return accum; }
and therefore
accum = & accum;
Another idea was to use
accum = [](& accum,& arg){ ...; return std::move(accum); }
But this will probably lead to something like:
accum = std::move(& accum);
Which looks very suspicious to me.
What is the correct way to write this in order to minimize the risk of unnecessarily creating temporary objects? I am not only interested in std :: string, I would be happy to get a solution that will probably work for any object that has copy and move constructors / assignments.