C ++ 11 std :: ref and the difference between the reference

std :: ref just try to simulate passed by reference, and can not really become a reference , in the case of non-template, std :: ref simply can not achieve reference semantics, and only when the template automatically deduce the type, ref can be used to replace the original packaging type reference_wrapper value type will be identified, and can implicitly converted reference_wrapper values quoted reference type.

std :: ref mainly on account of functional programming (e.g., std :: bind), in use, a direct copy of the parameters, rather than a reference

Representative examples which are thread
when the thread transfer methods such references, the outer layer must be passed by reference to ref, otherwise shallow copy.
 

Thread function parameter value by moving or copying. If reference parameters to be passed to the thread function, it must be packaged (e.g., using std :: ref or std :: cref).

Sample code:

// 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;
}

operation result:

 

Code Example 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;
}

 operation result:

Published 257 original articles · won praise 22 · views 90000 +

Guess you like

Origin blog.csdn.net/qq_24127015/article/details/104823522