In the following code I have a function foo
taking as argument a std::function
returning a big object (here a vector
) and uses it only to access its values. The big object may be built on-the-fly by fun
or be a reference to an existing object as the two lambda expressions in the main show.
I would like to optimize this code to avoid useless copies possibly by choosing the right return type of the std::function
.
If I use return by value, RVO optimizes out the copy and makes exactly what I want for the "build on-the-fly" case: no copies are done, the vector is built exactly where it needs to and later destroyed at the end of foo
. However, in the second case the compiler does copy the vector even if I don't really need it. The second case would be the perfect situation for a return-by-reference but this would break the first case since reference to temporary are evil.
I understand that making foo
directly taking a reference to the vector would solve the problem in this particular case but my use case is more complex. Is there a way to solve this?
#include <vector>
#include <iostream>
#include <functional>
struct myVec : public std::vector<double> {
using std::vector<double>::vector;
myVec(myVec const & v){
std::cout << "Copy ctor\n";
*this=v;
}
};
void foo(std::function<myVec(void)> fun){
for(auto & v : fun()){
std::cout << v << " ";
}
std::cout<<std::endl;
}
int main() {
foo([]()->myVec{return myVec(100,0.);});
myVec existing(100,1.);
foo([&existing]()->myVec{return existing;});
return 0;
}