#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
问题在于您的函数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};
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句