Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda capture list and copying

Tags:

c++

c++11

lambda

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?

like image 980
ixSci Avatar asked May 07 '26 23:05

ixSci


1 Answers

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;
}
like image 77
Mankarse Avatar answered May 10 '26 13:05

Mankarse



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!