There are two ways to use lambda function variable:
std::function<int(int, int)> x1 = [=](int a, int b) -> int{return a + b;};
//usage
void set(std::function<int(int, int)> x);
std::function<int(int, int)> get();
And:
std::function<int(int, int)>* x2 = new std::function<int(int, int)>([=](int a, int b) -> int{return a + b;});
//usage
void set(std::function<int(int, int)>* x);
std::function<int(int, int)>* get();
I would like to know what are the differences, because I do not know how the lambda function data is stored.
I would like to know the best way in terms of peformance, memory usage and the best way to pass a lambda function as argument or return lambda function.
I would prefer to use pointers if the size of the lambda function object is bigger than 4 or to avoid errors (if some kind of copy constructor is executed when I do an attribution or if some kind of destructor is executed when I do not want).
How should I declare lambda function variables?
EDIT
I want to avoid copies and moves, I want to continue to use the same function again.
How should I change this example?
int call1(std::function<int(int, int)> f){
return f(1, 2);
}
int call2(std::function<int(int, int)> f){
return f(4, 3);
}
std::function<int(int, int)>& recv(int s){
return [=](int a, int b) -> int{return a*b + s;};
}
int main(){
std::function<int(int, int)> f1, f2;
f1 = [=](int a, int b) -> int{return a + b;};
f2 = recv(10);
call1(f1);
call2(f1);
call1(f2);
call2(f2);
}
I cannot return reference in the function recv:
warning: returning reference to temporary
Is this a good solution?
int call1(std::function<int(int, int)>* f){
return (*f)(1, 2);
}