C++11 std::ref和引用的区别

std::ref只是尝试模拟引用传递,并不能真正变成引用,在非模板情况下,std::ref根本没法实现引用传递,只有模板自动推导类型时,ref能用包装类型reference_wrapper来代替原本会被识别的值类型,而reference_wrapper能隐式转换为被引用的值的引用类型。

std::ref主要是考虑函数式编程(如std::bind)在使用时,是对参数直接拷贝,而不是引用

其中代表的例子是thread
比如thread的方法传递引用的时候,必须外层用ref来进行引用传递,否则就是浅拷贝。
 

线程函数的参数按值移动或复制。如果引用参数需要传递给线程函数,它必须被包装(例如使用std :: ref或std :: cref)。

示例代码:

// threadTest.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <vector>
#include <thread>
#include <future>
#include <numeric>
#include <iostream>
#include <chrono>

void method(int &a) { a += 5; }

using namespace std;
int main()
{
	int a = 0;
	thread th(method, ref(a));
	th.join();
	cout << a << endl;
    return 0;
}

运行结果:

示例代码2:

// threadTest.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <vector>
#include <thread>
#include <future>
#include <numeric>
#include <iostream>
#include <chrono>
#include <functional>

using namespace std;

void f(int &n1, int &n2, const int &n3)
{
	cout << "In function:" << n1 << ' ' << n2 << ' ' << n3 << endl;
	++n1;
	++n2;
}

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;
	cout << "Before function: " << n1 << ' ' << n2 << ' ' << n3 << endl;
	bound_f();
	cout << "After function: " << n1 << ' ' << n2 << ' ' << n3 << endl;
    return 0;
}

 运行结果:

发布了257 篇原创文章 · 获赞 22 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/qq_24127015/article/details/104823522