jeudi 23 avril 2020

Reference is useless in std::bind?

//example

void f(int &n1, int& n2)
{
    n1++;
    n2++;
}
int main()
{
    int n1 = 1, n2 = 2;
    auto bound1 = std::bind(&f, n1, std::ref(n2));
    bound1();    // 1 3
    std::cout << n1  << n2 << endl;
    auto bound2 = std::bind(&f, std::placeholders::_1, std::ref(n2)); // 2 4
    bound2(n1);
    std::cout << n1  << n2 << endl;
}

My first question would be about the reference in function f, is it wrong to do std::bind on a function that receives a parameter by reference ?

Because in the code presented above the value of n1 does not change. After all i see if i put std::placeHolders::_1 value of n1 will be change. That is my second question std::placeHolders call std::ref ?

I know the title is not really suggestive...

Aucun commentaire:

Enregistrer un commentaire