Why doesn't bind work with link password?

I believe that reference does not work when using std :: bind. Here's an example.

int test;

void inc(int &i)
{
    i++;
}

int main() {
    test = 0;
    auto i = bind(inc, test);
    i();
    cout<<test<<endl; // Outputs 0, should be 1
    inc(test);
    cout<<test<<endl; // Outputs 1
    return 0;
}

      

Why isn't the variable incremented when called through a function created with std bind?

+3


source to share


1 answer


std::bind

copies the supplied argument, then passes the copy to your function. To pass a link to bind

, you need to use std::ref

:auto i = bind(inc, std::ref(test));



+5


source







All Articles