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 copy into the lambda, and one which occurs when the lambda (which has a Copy member) is copied in to the std::function.
If you want one copy and one move, you will need to make the Copy object be movable:
#include <iostream>
#include <functional>
struct Copy
{
Copy(){}
Copy(const Copy&)
{
std::cout << "Copied!\n";
}
Copy(Copy&&)
{
std::cout << "Moved!\n";
}
};
//Prints:
//Copied!
//Moved!
int main()
{
Copy copy;
std::function<void()> func = [=]{(void)copy;};
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With