【C++ 】std::ref()和std::cref()


  轉自綠色冰點C++11 std::ref使用場景

  C++本身有引用(&),為什么C++11又引入了std::ref(或者std::cref)?使用std::ref可以在模板傳參的時候傳入引用,否則只能傳值。主要是考慮函數式編程(如std::bind)在使用時,是對參數直接拷貝,而不是引用。如下例子:

復制代碼
#include <functional>
#include <iostream>
 
void f(int& n1, int& n2, const int& n3)
{
    std::cout << "In function: " << n1 << ' ' << n2 << ' ' << n3 << '\n';
    ++n1; // increments the copy of n1 stored in the function object
    ++n2; // increments the main()'s n2
    // ++n3; // compile error
}
 
int main()
{
    int n1 = 1, n2 = 2, n3 = 3;
    std::function<void()> bound_f = std::bind(f, n1, std::ref(n2), std::cref(n3));
    n1 = 10;
    n2 = 11;
    n3 = 12;
    std::cout << "Before function: " << n1 << ' ' << n2 << ' ' << n3 << '\n';
    bound_f();
    std::cout << "After function: " << n1 << ' ' << n2 << ' ' << n3 << '\n';
}
復制代碼

 

Output:

Output:
Before function: 10 11 12
In function: 1 11 12
After function: 10 12 12

  上述代碼在執行std::bind后,在函數f()中n1的值仍然是1,n2和n3改成了修改的值。說明std::bind使用的是參數的拷貝而不是引用。具體為什么std::bind不使用引用,可能確實有一些需求,使得C++11的設計者認為默認應該采用拷貝,如果使用者有需求,加上std::ref即可。

  &是類型說明符, std::ref 是一個函數,返回 std::reference_wrapper類型。另外std::cref() 用於const引用的版本。

 


免責聲明!

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



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