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 <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;
	//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传递了引用,如果函数本身只接受值类型参数,传递的仍然是值而不是引用。

 

 

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
C++中的std::bind是一个函数模板,用于创建一个可调用对象(函数对象或成员函数指针),并绑定其参数。它可以将一个函数或成员函数与一组参数绑定在一起,形成一个新的可调用对象。 std::bind的基本语法如下: ```cpp std::bind(Function, args...) ``` 其中,Function是要绑定的函数或成员函数指针,args是要绑定的参数。 使用std::bind可以实现以下功能: 1. 绑定普通函数的部分参数,生成一个新的可调用对象。 2. 绑定成员函数的对象指针和部分参数,生成一个新的可调用对象。 3. 绑定成员函数的对象引用和部分参数,生成一个新的可调用对象。 下面是一些示例: 1. 绑定普通函数的部分参数: ```cpp #include <iostream> #include <functional> void printSum(int a, int b) { std::cout << "Sum: " << a + b << std::endl; } int main() { auto printSumWith5 = std::bind(printSum, 5, std::placeholders::_1); printSumWith5(10); // 输出:Sum: 15 return 0; } ``` 2. 绑定成员函数的对象指针和部分参数: ```cpp #include <iostream> #include <functional> class MyClass { public: void printProduct(int a, int b) { std::cout << "Product: " << a * b << std::endl; } }; int main() { MyClass obj; auto printProductWith2 = std::bind(&MyClass::printProduct, &obj, std::placeholders::_1); printProductWith2(5); // 输出:Product: 10 return 0; } ``` 3. 绑定成员函数的对象引用和部分参数: ```cpp #include <iostream> #include <functional> class MyClass { public: void printDifference(int a, int b) { std::cout << "Difference: " << a - b << std::endl; } }; int main() { MyClass obj; auto printDifferenceWith3 = std::bind(&MyClass::printDifference, std::ref(obj), std::placeholders::_1); printDifferenceWith3(7); // 输出:Difference: 4 return 0; } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

C++程序员Carea

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值