I have a simple code:
#include <iostream>
#include <functional>
struct Copy
{
Copy(){}
Copy(const Copy&)
{
std::cout << "Copied!\n";
}
};
int main()
{
Copy copy;
std::function<void()> func = [=]{(void)copy;};
return 0;
}
And it calls copy-ctor 2 times and I want to have it only one time. I understand that I can use auto in this simplified example but I need to store it for some later use so auto is no option.
And my question: is there a way to store lambda with = capture list and have only one copy of the captured objects?
There are two copies: one to copy
copyinto the lambda, and one which occurs when the lambda (which has aCopymember) is copied in to thestd::function.If you want one copy and one move, you will need to make the
Copyobject be movable: