c++11 std::ref std::cref


參考:

C++已經有了引用操作符&為什么C++11還要引入std:ref

std::ref和std::cref使用

 

&是類型說明符,而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按引用傳遞

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM