我发现使用std :: bind时,引用传递往往不起作用.这是一个例子.
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;
}
Run Code Online (Sandbox Code Playgroud)
当通过使用std bind创建的函数调用时,为什么变量不会递增?
std::bind复制提供的参数,然后将副本传递给您的函数.为了传递引用bind你需要使用std::ref:auto i = bind(inc, std::ref(test));