mardi 2 février 2021

why std::bind will copy twice when pass by value?

Here is the sample code

class A
{
public:
    int a{ 3 };
    A() { std::cout << "con\n"; };
    A(const A&) { std::cout << "con2\n"; };
};


int main()
{
    std::function<void(A)> f = [](A a) {};
    A data;
    auto p = std::bind(f,data);
    p();
    return 0;
}

Here is the output

con
con2
con2
con2

I knew that the cause of the first three line output

  1. create the data object
  2. capture it as a member of object p
  3. pass the A object by value

but why it calls the constructor again?
BTW, the g++ and vc++ share the same behavior

Aucun commentaire:

Enregistrer un commentaire