Note: This article is available in Chinese only. 本文暂无英文版本。
View original
起因是在看《CplusplusConcurrencyInAction_PracticalMultithreading》的时候,里面讲到初始化 std::thread 的时候,如果 thread function 的参数列表中有引用,需要传入 std::ref 才可以得到符合预期的结果。
查阅发现 std::ref 是用来生成 std::reference_wrapper。按照 cppreference 上的话来说
std::reference_wrapper是包装引用于可复制、可赋值对象的类模板。它常用作将容器存储入无法正常保有引用的标准容器(类似 std::vector )的机制。
用人话来说,就是有的时候一些地方(比如 STL 容器中传值,又比如 std::bind)会默认使用复制,这可能与我们想使用引用的期望不符。
具体见下面的几个例子:
1#include <functional>
2#include <iostream>
3
4void f(int& n1, int& n2, const int& n3)
5{
6 std::cout << "In function: " << n1 << ' ' << n2 << ' ' << n3 << '\n';
7 ++n1; // increments the copy of n1 stored in the function object
8 ++n2; // increments the main()'s n2
9 // ++n3; // compile error
10}
11
12int main()
13{
14 int n1 = 1, n2 = 2, n3 = 3;
15 std::function<void()> bound_f = std::bind(f, n1, std::ref(n2), std::cref(n3));
16 n1 = 10;
17 n2 = 11;
18 n3 = 12;
19 std::cout << "Before function: " << n1 << ' ' << n2 << ' ' << n3 << '\n';
20 bound_f();
21 std::cout << "After function: " << n1 << ' ' << n2 << ' ' << n3 << '\n';
22}输出:
1Before function: 10 11 12
2In function: 1 11 12
3After function: 10 12 12我们发现直接传进去的参数 n1 的值没有改变,而使用 std::ref 传进去的参数结果符合预期。
n1 的值不符合预期的原因是,在调用 std::bind 的时候,会先将参数复制一份;然后传入函数 f 时,传入的不是在 main 函数中定义的 n1 的引用,而是对 n1 复制一份得到的临时变量的引用。在函数 f 中对 n1 的修改只会改到这份拷贝,而不会改变原来的 n1。
下面是一个关于 std::reference_wrapper 的例子
1#include <algorithm>
2#include <list>
3#include <vector>
4#include <iostream>
5#include <numeric>
6#include <random>
7#include <functional>
8
9int main()
10{
11 std::list<int> l(10);
12 std::iota(l.begin(), l.end(), -4);
13
14 std::vector<std::reference_wrapper<int>> v(l.begin(), l.end());
15 // 不能在 list 上用 shuffle (要求随机访问),但能在 vector 上使用它
16 std::shuffle(v.begin(), v.end(), std::mt19937{std::random_device{}()});
17
18 std::cout << "Contents of the list: ";
19 for (int n : l) std::cout << n << ' '; std::cout << '\n';
20
21 std::cout << "Contents of the list, as seen through a shuffled vector: ";
22 for (int i : v) std::cout << i << ' '; std::cout << '\n';
23
24 std::cout << "Doubling the values in the initial list...\n";
25 for (int& i : l) {
26 i *= 2;
27 }
28
29 std::cout << "Contents of the list, as seen through a shuffled vector: ";
30 for (int i : v) std::cout << i << ' '; std::cout << '\n';
31}输出:
1Contents of the list: -4 -3 -2 -1 0 1 2 3 4 5
2Contents of the list, as seen through a shuffled vector: -1 2 -2 1 5 0 3 -3 -4 4
3Doubling the values in the initial list...
4Contents of the list, as seen through a shuffled vector: -2 4 -4 2 10 0 6 -6 -8 8最后我们回到开始:参数通过创建 std::thread 传给 thread function 的时候,默认情况下仍然会被拷贝一份,与上面 std::bind 的情况类似,因此需要使用 std::ref。
参考资料:
- 《CplusplusConcurrencyInAction_PracticalMultithreading》2.2 节
- std::ref
- std::reference_wrapper
- C++ Difference between std::ref(T) and T&?