尝试引用已删除的函数

Attempt to reference a deleted function

虽然 运行 一个线程我得到了这个错误。我已经使用了参考 fstream 作为 readFile 函数的参数以避免复制 构造函数调用也。我仍然遇到同样的错误,怎么办?

void readFile(fstream& fileStream)
{    
    // some code
}

int _tmain(int argc, _TCHAR* argv[])
{
    fstream stream;  
    readFile(stream);   
    thread oddPrint(readFile, stream);
    oddPrint.join();     
    getchar();

    return 0;
}

阅读有关 thread constructor 的参考资料。在下一行

thread oddPrint(readFile, stream);

在调用 thread 构造函数时 stream 对象是按值传递的,但是 fstream class 没有复制操作所以你得到了错误。如果你想将不可复制的对象作为参数传递,你必须使用 std::refstd::cref 包装器:

thread oddPrint(readFile, std::ref(stream));