std::ref只是尝试模拟引用传递,并不能真正变成引用,在非模板情况下,std::ref根本没法实现引用传递,只有模板自动推导类型时,ref能用包装类型reference_wrapper来代替原本会被识别的值类型,而reference_wrapper能隐式转换为被引用的值的引用类型。
std::ref主要是考虑函数式编程(如std::bind)在使用时,是对参数直接拷贝,而不是引用
其中代表的例子是thread
比如thread的方法传递引用的时候,必须外层用ref来进行引用传递,否则就是浅拷贝。
线程函数的参数按值移动或复制。如果引用参数需要传递给线程函数,它必须被包装(例如使用std :: ref或std :: cref)。
#include <functional> #include <iostream> #include<cstring> #include<string.h> #include<memory> #include<atomic> #include<unordered_map> #include<mutex> #include <thread> #include <string> void method(int & a){ a += 5;} using namespace std; int main(){ int a = 0; // each reference used by the threads would refer to the same object. thread th(method,ref(a)); th.join(); cout << a <<endl; /* * I could compile your code successfully with MSVC2013. However, thread() works passing copies of its argument to the new thread. This means that if your code would compile on your compiler, each thread wourd run with its own copy of ht, so that at the end, main's a would be empty. GCC doesn't compile with this weird message. */ /*thread th2(method, a); //浅拷贝 th2.join(); cout << a <<endl;*/ return 0; }
/** @file bindRefT.cpp * @note * @brief * @author * @date 2019-8-8 * @note * @history * @warning */ #include <functional> #include <iostream> //std::ref主要是考虑函数式编程(如std::bind)在使用时,是对参数直接拷贝,而不是引用 void f(int& n1, int& n2, const int& n3) { std::cout << "In function: " << n1 << ' ' << n2 << ' ' << n3 << '\n'; ++n1; // increments the copy of n1 stored in the function object ++n2; // increments the main()'s n2 // ++n3; // compile error } int main() { int n1 = 1, n2 = 2, n3 = 3; std::function<void()> bound_f = std::bind(f, n1, std::ref(n2), std::cref(n3)); n1 = 10; n2 = 11; n3 = 12; std::cout << "Before function: " << n1 << ' ' << n2 << ' ' << n3 << '\n'; bound_f(); std::cout << "After function: " << n1 << ' ' << n2 << ' ' << n3 << '\n'; }
分类:
c++11/14/17/20
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
2021-09-16 Go并发编程--正确使用goroutine
2021-09-16 Reliable UDP一览:那些能替代TCP的RUDP方案
2020-09-16 Docker简介
2014-09-16 CMAKE的使用
2014-09-16 vnc server配置、启动、重启与连接,图形管理linux系统
2014-09-16 Linux下VNC的安装和开机启动
2014-09-16 用命令行方式关闭linux防火墙