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

1112 ワード

std::bindは常にパラメータをコピーしますが、呼び出し元はstd::refを使用してstd::bindへの参照の伝達を実現できます.
原文は以下の通りである:std::bind always copies its arguments,but callers can achieve the effect of having an argument stored by reference by applying std::refto 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を使用して参照を渡しますが、関数自体が値タイプパラメータのみを受け入れる場合、参照ではなく値を渡します.