为什么bind不能通过引用传递? [英] Why does bind not work with pass by reference?

查看:539
本文介绍了为什么bind不能通过引用传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现通过引用的方式倾向于不工作时使用std :: bind。这是一个例子。

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

为什么变量在通过std bind ?

Why isn't the variable incrementing when called via the function created with std bind?

推荐答案

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

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

这篇关于为什么bind不能通过引用传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆