C++11 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 <iostream>
#include <functional>
 
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;
	auto b_fun = std::bind(fun, a, std::ref(b), std::ref(c)); //a被bind传值 b被ref传引用 c被fun传值
	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传递了引用,如果函数本身只接受值类型参数,传递的仍然是值而不是引用。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值