【问题标题】:c++ threading 'no matching overloaded function found' [duplicate]c ++线程'找不到匹配的重载函数'[重复]
【发布时间】:2020-05-23 15:04:27
【问题描述】:
#include <thread>

void f(int*& ptr)
{
    ptr = new int[4];
    ptr[0] = 0;
    ptr[1] = 1;
    ptr[2] = 2;
    ptr[3] = 3;
}

int main()
{
    int* ptr;

    std::thread thread{ f, ptr };
    thread.join();

    delete[] ptr;
    return 0;
}

我不明白我错过了什么。我尝试了参考或非参考的不同组合,检查了我是否具有与文档中相同的格式。没有。我仍然收到此错误:

Error C2672: 'std::invoke': no matching overloaded function found

【问题讨论】:

  • 请以文本的形式发布错误信息。 从不作为图像。谢谢。
  • 您必须至少使用std::ref(ptr) 否则它将按值传递(但它可能会失败

标签: c++ multithreading c++11


【解决方案1】:

问题是你的函数f 引用了一个指针。但是,线程不能存储引用参数以供以后调用,因此您必须改用指向指针的指针。

#include <thread>

void f(int** ptr)
{
    *ptr = new int[4];
    *ptr[0] = 0;
    *ptr[1] = 1;
    *ptr[2] = 2;
    *ptr[3] = 3;
}

int main()
{
    int* ptr;

    std::thread thread{f, &ptr};
    thread.join();

    delete[] ptr;
    return 0;
}

注意:您可以使用更漂亮的方式初始化数组:

*ptr = new int[] {0, 1, 2, 3};

【讨论】:

  • 请注意,您可以使用std::ref 向线程“传递引用”
猜你喜欢
  • 2018-04-30
  • 2021-09-09
  • 1970-01-01
  • 2020-09-22
  • 2018-08-01
  • 2018-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多