4

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?

DeepDeadpool
  • 1,441
  • 12
  • 36
  • Use [`std::ref`](http://en.cppreference.com/w/cpp/utility/functional/ref) to pass a reference to std::bind! – Caninonos Aug 04 '15 at 13:46

1 Answers1

7

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));

ixSci
  • 13,100
  • 5
  • 45
  • 79