Why does bind not work with pass by reference? [duplicate]

帅比萌擦擦* 提交于 2019-12-20 02:43:16

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/31810985/why-does-bind-not-work-with-pass-by-reference

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!