以 std::ifstream 作为参数的 std::thresd 中出现错误

问题描述 投票:0回答:1

我使用了 vs2019 的 CppCLRWinformsProjekt 扩展。我需要实现一个从文件读取并将数据存储在某些变量中的线程。

线程函数如下:

private: void startThread(std::ifstream file)
{  }

以及线程创建代码:

std::ifstream file(fn, std::ios::binary);
std::thread thread(startThread, file);

但是最后一行

startThread
有一些问题!

构造函数“std::thread::thread”的实例与参数列表不匹配

参数类型为:(void (std::ifstream file), std::ifstream)

'CppCLRWinformsProjekt::Form1::startThread':非标准语法;使用“&”创建指向成员的指针。

我尝试将

file
作为指针传递,但没有任何改变。

我根据一些网站上的教育方法实现了代码。

如何消除这些错误?

c++ stdthread
1个回答
0
投票
void startThread(std::ifstream file)

如您所知,默认情况下,C++ 中的所有函数参数都是按值传递的。这意味着它们被有效复制。

std::ifstream
的复制构造函数被删除。您无法复制
std::ifstream
对象。

确实可以使用参考参数:

void startThread(std::ifstream &file)

然而,当涉及

std::thread
时,这仍然不够。线程函数的所有参数都被复制到新的执行线程中。只有这样它们才会被传递到实际的线程函数,因此总是会创建一个副本。所以,你仍然不能直接通过
std::ifstream

这恰好是

std::reference_wrapper
的用途:

std::thread thread{startThread, std::ref{file}};

在所有情况下,请记住,

file
最终是通过引用传递的,并且只要新的执行线程可以引用它,就必须保留在范围内并且不会被销毁。这有其自身的含义,但超出了您的问题范围。有关更多信息,请参阅您最喜欢的涵盖高级多线程概念的 C++ 教科书。

© www.soinside.com 2019 - 2024. All rights reserved.