Skip to main content
  1. Posts/

[C++11 ] std::ref&&std::reference_wrapper notes

·3 mins
Note: This article is available in Chinese only. 本文暂无英文版本。 View original

起因是在看《CplusplusConcurrencyInAction_PracticalMultithreading》的时候,里面讲到初始化std::thread的时候,如果thread funtion的参数列表中有引用,需要传入std::ref才可以得到符合预期的结果。

查阅发现std::ref是用来生成std::reference_wrapper。 按照 cppreference 上的话来说

std::reference_wrapper 是包装引用于可复制、可赋值对象的类模板。它常用作将容器存储入无法正常保有引用的标准容器(类似 std::vector )的机制。

用人话来说,就是有的时候一些地方(比如STL容器中传值,又比如std::bind)会默认使用复制,这可能与我们想使用引用的期望不符。

具体见下面的几个例子:

 1    #include <functional>
 2    #include <iostream>
 3     
 4    void 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     
12    int 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    }
23Before function: 10 11 12
24In function: 1 11 12
25After function: 10 12 12

我们发现直接传进去的参数n1的值没有改变,而使用std::ref传进去的值的结果符合预期。

n1的值不符合预期的原因是,在调用std::bind的时候,会先将参数复制一份,然后传入函数f时,传入的不是在main函数中定义的n1的引用,而是对n1复制了一份得到的临时变量的引用。在函数f中对n1的修改只会使得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     
 9    int 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    }
32    
33    
34    Contents of the list: -4 -3 -2 -1 0 1 2 3 4 5 
35    Contents of the list, as seen through a shuffled vector: -1 2 -2 1 5 0 3 -3 -4 4 
36    Doubling the values in the initial list...
37    Contents of the list, as seen through a shuffled vector: -2 4 -4 2 10 0 6 -6 -8 8

最后我们回到开始,将参数在通过创建std::thread传给thread funtion的时候,参数默认情况下仍然是被拷贝了一份,与上面std::bind的情况类似,因此需要使用std::ref

参考资料:

  * 《CplusplusConcurrencyInAction_PracticalMultithreading》2.2节
  * [std::ref](https://zh.cppreference.com/w/cpp/utility/functional/ref)
  * [std::reference_wrapper](https://zh.cppreference.com/w/cpp/utility/functional/reference_wrapper)
  * [C++ Difference between std::ref(T) and T&?](https://stackoverflow.com/questions/33240993/c-difference-between-stdreft-and-t)
  * 

Related

[C++11] promise && future leanrning notes

用人话就是,主线程传给附属线程一个promise Object,然后主线程想要获取附属线程set给promise Object的值(也就是该线程返回的某个结果),需要通过主线程中的promise object 得到对应的future object(每个promise 对应一个 future),然后调用future 的get方法。如果附属线程没有执行作为参数传入的promise的set方法去返回结果,那么程序就会block住。

把二进制文件按字节读到vector中

·1 min
1 std::vector<unsigned char> readFromFile1(const char* filePath) { 2 FILE* file = fopen(filePath, "rb"); 3 std::vector<unsigned char> result; 4 if (file == nullptr) { 5 return result; 6 } 7 8 // 获取文件大小,尽量一次读完 9 size_t fileSize = getFileSize(file); 10 if (fileSize != 0) { 11 result.resize(fileSize); 12 size_t n = fread(&result[0], 1, fileSize, file); 13 assert(n <= fileSize); 14 if (n != fileSize) { 15 result.resize(n); 16 } 17 } 18 19 // 在读取过程当中,有可能文件大小有变化,再尝试读取 20 const size_t read_len = 1024; 21 char buf[read_len]; 22 for (;;) { 23 size_t n = fread(buf, 1, read_len, file); 24 result.insert(result.end(), buf, buf + n); 25 if (n < read_len) { 26 break; 27 } 28 } 29 fclose(file); 30 return result; 31 } 另外一种C++风格,但是性能较差的方法: