首页 > 解决方案 > 使用 std::async 调用函数时,引用变量的地址不同

问题描述

在下面的代码片段中,vin函数的地址与 in使用的when 的print地址相同,但传递的 when 不同astd::ref(a)std::asynca

#include <iostream>
#include <future>

void print (const int& v)
{
    std::cout  << "&v = " << &v << "\n";
}


int main()
{
    int a = 10;

    auto f = std::async(print, std::ref(a));
    f.get();
    
    std::cout  << "&a = " << &a << "\n";

    return 0;
}

输出

&v = 0x7ffd3b5000b4
&a = 0x7ffd3b5000b4

但是当我删除时std::ref,地址是不同的

auto f = std::async(print, a);

输出

&v = 0x55586497cef8
&a = 0x7ffee2e3dadc

问题:

参考:通过引用将参数传递给 std::async 失败

标签: c++multithreadingc++11c++17

解决方案


推荐阅读