C++-std::ref
1、函数式编程如std::bind、std::thread传参数等使用时,是对参数直接拷贝而不是引用
如:
#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 = 1, n2 = 1, n3 = 1; 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[1] n2[1] n3[1] In function: n1[1] n2[1] n3[1] In function end: n1[2] n2[2] n3[1] After function: n1[1] n2[2] n3[1]
n1是普通值传递;n2是引用传递;n3是const引用传递
参考:https://blog.csdn.net/lmb1612977696/article/details/81543802
长风破浪会有时,直挂云帆济沧海!
可通过下方链接找到博主
https://www.cnblogs.com/judes/p/10875138.html