bind引用传参
std::bind
的函数参数默认使用的是拷贝, 如果需要使用引用,则需要配合std::ref
。
下面一个例子,帮助理解。print2函数负责输出参数的值,且参数都是引用, print2函数内完成对参数的自增
#include <functional>
#include <iostream>
void print2(int& a, int& b)
{
std::cout << "calling: a=" << a << ", b=" << b << "\n";
++a;
++b;
}
int main(int argc, char* argv[], char* env[])
{
int a = 1;
int b = 2;
auto func2 = std::bind(print2, a, std::ref(b));
std::cout << "before a=" << a << ", b=" << b << "\n";
func2();
std::cout << "after a=" << a << ", b=" << b << "\n";
return 0;
}
调用时,尽管都采用了传入引用的方式,但略有不同。参数a使用的是传统的方式,参数b采用的是 std::ref的方式。 观察输出结果
before a=1, b=2
calling: a=1, b=2
after a=1, b=3
可以看到,std::bind的参数是以 拷贝的方式,使用 std::ref 的方式可以实现参数在std::bind的引用。