mardi 1 décembre 2015

C++ lambda two copy constructor calls

I have the following code snippet.

#include <iostream>
#include <functional>
using namespace std;

struct A
{
    A() { cout << "A "; data = 1; }
    A(const A& a) { cout << "cA "; data = a.data; }
    ~A() { cout << " dA"; }
    int data;
};

void f(A& a, function<void(A)> f)
{
    cout << "(";
    f(a);
    cout << ")";
}

int main()
{
    A temp;
    auto fun = [](A a) {cout << a.data;};
    f(temp, fun);
}

The output is:

A (cA cA 1 dA dA) dA

Why is temp copied twice?

I am using Visual C++ (vc140).

Aucun commentaire:

Enregistrer un commentaire