There are two ways to use a lambda function variable:
std::function<int(int, int)> x1 = [=](int a, int b) -> int{return a + b;};
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;});
void set(std::function<int(int, int)>* x);
std::function<int(int, int)>* get();
I would like to know what the differences are because I do not know how the data of the lambda function is stored.
I would like to know the best way in terms of performance, memory usage and the best way to pass a lambda function as an argument or return a lambda function. I would prefer to use pointers if the size of the object of the lambda function is greater than 4 or to avoid errors (if some copy constructor is executed when I do the attribution or if some kind of destructor is done when I don't want to).
How to declare lambda function variables?
EDIT
I want to avoid copying and moving, I want to continue to use the same function again.
How do 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);
}
recv:
warning: returning reference to temporary
?
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 new std::function<int(int, int)>([=](int a, int b) -> int{return a*b + s;});
}
int main(){
std::function<int(int, int)> f1 = [=](int a, int b) -> int{return a + b;};
std::function<int(int, int)> *f2 = recv(10);
call1(&f1);
call2(&f1);
call1(f2);
call2(f2);
delete f2;
}
EDIT ()
- , . , .