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