參考:
C++已經有了引用操作符&為什么C++11還要引入std:ref
&是類型說明符,而std::ref是一個函數,返回std::reference_wrapper(類似於指針)
為什么需要std::ref?(std::cref類似)
主要是考慮到c++11中的函數式編程,例如:std::bind
std::bind在使用時,是對參數直接拷貝,而不是引用
發現這個問題的契機是在使用thread的標准庫時
#include<iostream> #include<thread> #include<string> using namespace std; void foo( int &a) { cout<<"thread :"<< a++ <<endl; } int main() { int num = 0; thread t1(foo, std::ref(num)); thread t2(foo, std::ref(num)); t1.join(); t2.join(); return 0; }
默認是按值傳遞,需要通過std::ref按引用傳遞