Search code examples
c++stdbind

Why does bind not work with pass by reference?


I find pass by reference tends not to 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 incrementing when called via the function created with std bind?


Solution

  • std::bind copies the argument provided, then it passes the copy to your function. In order to pass a reference to bind you need to use std::ref:auto i = bind(inc, std::ref(test));