1. 程式人生 > >c++11 std::ref使用場景

c++11 std::ref使用場景

C++本身有引用(&),為什麼C++11又引入了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即可。