ixSci
ixSci

Reputation: 13698

Lambda capture list and copying

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?

Upvotes: 3

Views: 1446

Answers (1)

Mankarse
Mankarse

Reputation: 40613

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;
}

Upvotes: 5

Related Questions