为什么绑定无法通过引用传递?

时间:2015-08-04 13:42:47

标签: c++ stdbind

我发现使用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;
}

当通过使用std bind创建的函数调用时,为什么变量不会递增?

1 个答案:

答案 0 :(得分:5)

std::bind复制提供的参数,然后将副本传递给您的函数。要传递对bind的引用,您需要使用std::refauto i = bind(inc, std::ref(test));

相关问题