小编yuh*_*hao的帖子

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

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

#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() 呢?

c++ multithreading reference-wrapper

3
推荐指数
1
解决办法
696
查看次数

标签 统计

c++ ×1

multithreading ×1

reference-wrapper ×1