1. 程式人生 > 實用技巧 >std::ref 和 std::cref 的使用

std::ref 和 std::cref 的使用

結論:

std::ref:用於包裝按引用傳遞的值。

std::cref:使用者包裝按const引用傳遞的值。

對於std::bind或std::thread中只能使用std::ref 和 std::cref 不能使用&。

std::ref 和 std::cref 只是嘗試模擬引用傳遞,並不能真正變成引用,在非模板情況下,std::ref根本沒法實現引用傳遞,只有模板自動推到型別時,ref能包裝型別reference_wrapper來代替原本會被識別的值型別,而reference_wrapper能隱式轉換為被引用的值的引用型別,但是並不能被用作 & 型別。

#include <functional>
#include 
<iostream> void f(int& n1, int& n2, const int& n3) { std::cout << "In function: n1[" << n1 << "] n2[" << n2 << "] n3[" << n3 << "]" << std::endl; ++n1; // 增加儲存於函式物件的 n1 副本 ++n2; // 增加 main() 的 n2 //++n3; // 編譯錯誤 std::cout << "
In function end: n1[" << n1 << "] n2[" << n2 << "] n3[" << n3 << "]" << std::endl; } int main() { int n1 = 1, n2 = 1, n3 = 1; std::cout << "Before function: n1[" << n1 << "] n2[" << n2 << "] n3[" << n3 << "
]" << std::endl; std::function<void()> bound_f = std::bind(f, n1, std::ref(n2), std::cref(n3)); bound_f(); std::cout << "After function: n1[" << n1 << "] n2[" << n2 << "] n3[" << n3 << "]" << std::endl; }

執行結果:

Before function: n1[1]     n2[1]     n3[1]
In function: n1[1]    n2[1]    n3[1]
In function end: n1[2]     n2[2]     n3[1]
After function: n1[1]     n2[2]     n3[1]

資料:

https://www.jianshu.com/p/277675675593

https://blog.csdn.net/lmb1612977696/article/details/81543802