C++ 引用包装器作为函数参数

yuh*_*hao 3 c++ multithreading reference-wrapper

根据我的理解,引用包装器只是引用的包装器,没有什么特别的。但是,当作为函数参数传递时,为什么它被视为函数内部的引用本身(而不是包装器)呢?

#include <iostream>
#include <functional>
using namespace std;

void f(int& x){
    cout<<"f on int called"<<endl;
}

void f(reference_wrapper<int>& x){
    cout<<"f on wrapper called"<<endl;
}

int main(){
    int x = 10;
    f(ref(x)); // f on int called, why?

    reference_wrapper<int> z = ref(x);
    f(z); // f on wrapper called, this makes sense though
}

Run Code Online (Sandbox Code Playgroud)

为什么 ref(x) 在函数调用中被视为 x 本身?我遇到这个问题是因为我试图理解在不同线程之间传递数据时 ref() 的使用。我认为 ref() 是必要的,因此任何带有“&”的函数参数都不需要重写以避免线程相互干扰。但是为什么线程可以将 ref(x) 视为 x 而不使用 x.get() 呢?

son*_*yao 5

f(ref(x)); // f on int called, why?
Run Code Online (Sandbox Code Playgroud)

因为std::reference_wrapper有一个到存储引用的转换运算符;ref(x)返回一个std::reference_wrapper,它可以隐式转换为int&

void f(reference_wrapper<int>& x)接受对非常量的左值引用,std::ref按值返回,即它返回的是一个右值,不能绑定到对非常量的左值引用。然后f(ref(x));调用第一个重载f而不是第二个重载。如果你将其更改为void f(reference_wrapper<int> x)void f(const reference_wrapper<int>& x)那么它将被调用。

居住