在没有复制构造函数的对象的成员函数中开始 std::thread

Start std::thread in member function of object that does not have a copy constructor

我想在一个没有复制构造函数的对象的成员函数处启动一个 std::thread。在成员函数处启动线程的标准方法(参见示例 Start thread with member function) needs a copy constructor. I thought I could get around this by using std::ref (see for example std::thread pass by reference calls copy constructor),但运气不好。

这是我的代码。线程 t1 有效,但 t2 无效。如果我尝试取消注释这两行,它会给出:

error: attempt to use a deleted function 
__invoke(_VSTD::move(_VSTD::get<0>(__t)), _VSTD::move(_VSTD::get<_Indices>(__t))...); ^
/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/thread:357:5: note: 
in instantiation of function template specialization
'std::__1::__thread_execute<void (Dummy::*)(), std::__1::reference_wrapper<Dummy> , 1>' 
requested here __thread_execute(*__p, _Index()); ^ 
etc.

如何直接在 print() 启动线程而不需要 uselessFunction

另外,我想更好地理解错误。编译器在抱怨哪个 "deleted function"?

#include <iostream>
#include <thread>
using std::cout;
using std::endl;

class Dummy {
public:
    std::atomic<bool> flag;  // atomic kills implicitly created copy constructor
    void print() { std::cout << "hello!" << std::endl; }
};

void uselessFunction(Dummy &d) {
    d.print();
}

int main() {
    Dummy d{};
    std::thread t1(uselessFunction, std::ref(d));  // this works
    // std::thread t2(&Dummy::print, std::ref(d)); // does not work
    t1.join();
    // t2.join();
}

std::thread使用std::invoke调用函数。 std::invoke 足够聪明,能够获取指向对象的指针并使用它调用成员函数。这意味着您可以将 t2 更改为

std::thread t2(&Dummy::print, &d);

并获得正确的行为。