C++11 std::bind std::ref

std::bind 总是拷贝其参数,但是,调用者可以使用std::ref来实现传递引用给std::bind,翻译自《Effective Modern C++:改善C++11和C++14的42个具体做法》

原文如下:std::bind always copies its arguments, but callers can achieve the effect of having an argument stored by  reference by applying std::ref to it.

示例代码:

#include 
#include 

void fun(int& _a, int& _b, int _c)
{
	_a++;
	_b++;
	_c++;

	std::cout << "in    fun a:" << _a << " b:" << _b << " c:" << _c << std::endl;
}

int main()
{

	int a = 1, b = 1, c = 1;
	//a被bind传值
	//b被ref传引用
	//c被fun传值
	auto b_fun = std::bind(fun, a, std::ref(b), std::ref(c));
	b_fun();

	std::cout << "after fun a:" << a << " b:" << b << " c:" << c << std::endl;

	return 0;
}

输出:

in fun a:2 b:2 c:2
after fun a:1 b:2 c:1
请按任意键继续. . .

结论:

a std::bind总是使用值拷贝的形式传参,哪怕函数声明为引用

b std::bind可以使用std::ref来传引用

c std::bind虽然使用了std::ref传递了引用,如果函数本身只接受值类型参数,传递的仍然是值而不是引用。

 

 

你可能感兴趣的:(C++,11)