转载于:https://blog.csdn.net/lmb1612977696/article/details/81543802

std::ref和std::cref

解释:

std::ref 用于包装按引用传递的值。

std::cref 用于包装按const引用传递的值。

为什么需要std::ref和std::cref
bind()是一个函数模板,它的原理是根据已有的模板,生成一个函数,但是由于bind()不知道生成的函数执行的时候,传递进来的参数是否还有效。所以它选择参数值传递而不是引用传递。如果想引用传递,std::ref和std::cref就派上用场了。

 #include <functional>
#include <iostream> void f(int& n1, int& n2, const int& n3)
{
std::cout << "In function: n1[" << n1 << "] n2[" << n2 << "] n3[" << n3 << "]" << std::endl;
++n1; // 增加存储于函数对象的 n1 副本
++n2; // 增加 main() 的 n2
//++n3; // 编译错误
std::cout << "In function end: n1[" << n1 << "] n2[" << n2 << "] n3[" << n3 << "]" << std::endl;
} int main()
{
int n1 = , n2 = , n3 = ;
std::cout << "Before function: n1[" << n1 << "] n2[" << n2 << "] n3[" << n3 << "]" << std::endl;
std::function<void()> bound_f = std::bind(f, n1, std::ref(n2), std::cref(n3));
bound_f();
std::cout << "After function: n1[" << n1 << "] n2[" << n2 << "] n3[" << n3 << "]" << std::endl;
}

输出:

 Before function: n1[]     n2[]     n3[]
In function: n1[] n2[] n3[]
In function end: n1[] n2[] n3[]
After function: n1[] n2[] n3[]

分析:

n1是值传递,函数内部的修改对外面没有影响。
n2是引用传递,函数内部的修改影响外面。
n3是const引用传递,函数内部不能修改。

最新文章

  1. LeetCode 299 Bulls and Cows
  2. centos6.5和centos7如何搭建php环境
  3. 给自己的XTC820摆拍一下。
  4. sql:劳务统计各分公司管理费用明细合计(等同汇总报表)
  5. Oracle建表脚本记录
  6. 七个结构模式之外观模式(Facade Pattern)
  7. 基本概率分布Basic Concept of Probability Distributions 5: Hypergemometric Distribution
  8. UIScrollView 原理详解
  9. Oracle10g新特性——正则表达式 - 转
  10. 【总结】学习Socket编写的聊天室小程序
  11. Oracle数据库备份手册
  12. hadoop2.6.0 --- 64位源代码
  13. Hadoop学习之shuffle过程
  14. python http请求
  15. 伪验证码(含随机验证码方法)js+css
  16. Java中的深克隆和浅克隆
  17. 1.HTTP协议|web框架
  18. 多态使用时,父类多态时需要使用子类特有对象。需要判断 就使用instanceof
  19. mui框架(一)
  20. Java如何显示线程状态?

热门文章

  1. saltstack集合
  2. rsync命令 SCP命令
  3. [HTML5] input标签 disable属性
  4. PDO连接不上又不报错的问题
  5. Leetcode:105. 从前序与中序遍历序列构造二叉树&amp;106. 从中序与后序遍历序列构造二叉树
  6. AOP in .NET
  7. 【React Native】使用react-native-wechat 进行微信好友、微信朋友圈进行分享
  8. Shiro -- (二) 身份验证基本流程
  9. MySQL中的执行计划explain
  10. Java架构师必看,超详细的架构师知识点分享!