C++ Difference between std::ref(T) and T&?

后端 未结 3 1314
既然无缘
既然无缘 2021-01-29 22:30

I have some questions regarding this program:

#include 
#include 
#include 
using namespace std;
template &l         


        
3条回答
  •  心在旅途
    2021-01-29 23:34

    std::reference_wrapper is recognized by standard facilities to be able to pass objects by reference in pass-by-value contexts.

    For example, std::bind can take in the std::ref() to something, transmit it by value, and unpacks it back into a reference later on.

    void print(int i) {
        std::cout << i << '\n';
    }
    
    int main() {
        int i = 10;
    
        auto f1 = std::bind(print, i);
        auto f2 = std::bind(print, std::ref(i));
    
        i = 20;
    
        f1();
        f2();
    }
    

    This snippet outputs :

    10
    20
    

    The value of i has been stored (taken by value) into f1 at the point it was initialized, but f2 has kept an std::reference_wrapper by value, and thus behaves like it took in an int&.

提交回复
热议问题