I was thinking of developing some named parameter code, but it got me thinking of some code like the following:
#include <utility>
int main()
{
using std::make_pair;
auto x = make_pair(1, make_pair(2, make_pair(3, make_pair(4,5))));
}
Now, a naive implementation of this would do "make_pair(4,5)" first, then copy the result into the second element of "make_pair(3, ...)", and then copy that into the second element of "make_pair(2, ...)" etc.
This would result in O(n^2) performance unfortunately, with a lot of unnecessary copies. I can't see how (named) return value optimization helps here either.
Ideally, make_pair(4,5)
realizes it's going to be in the last spot of x
, and constructs itself in that place.
Taking this further:
#include <utility>
int main()
{
using std::make_pair;
auto&& x1 = make_pair(3, make_pair(4,5));
auto x2 = make_pair(1, make_pair(2, std::move(x1)));
}
I'd like to avoid the copies in code like this also.
Is this optimization so obvious that I should assume compilers perform it or is there another way I should be coding this to avoid the copies?