Walkthrough C ++ lambdas

This is only a theoretical question. When I execute this code:

#include <functional>
#include <cstdio>

struct A {

    int value = 100;

    A() {
        printf("A\n");
    }

    A(const A& a) {
        printf("copy A\n");
    }

    ~A() {
        printf("~A\n");
    }
};

void function(std::function<int()> lambda) {
    printf("%d\n", lambda());
}

int main()
{
    A a;
    auto lambda = [a]() -> int {
        return a.value;
    };

    function(lambda);

    return 0;
}

Output:

A
copy A
copy A
copy A
100
~A
~A
~A
~A

And my question is: why is struct A copied 3 times, not 2? One instance takes a lambda capture, the second takes a passing argument to the function, and the third takes what?

+4
source share
1 answer

You will see the same number of copy operations if you change the code as follows:

int main()
{
    A a;
    auto&& lambda = [a]() -> int {
        return a.value;
    };
    std::function<int()>{lambda};
}

The first copy / move construct occurs when creating a lambda. The second and third copy / move constructs occur during the construction of the std :: function. According to N3690, the std :: function constructor used is as follows:

template <class F> function(F);

, / . / .

(, ), /. , .

template <typename Arg> function(Arg&&);
+2

Source: https://habr.com/ru/post/1532961/


All Articles