[英]Start std::thread in member function of object that does not have a copy constructor
I want to start a std::thread
at a member function of an object that does not have a copy constructor. 我想在没有副本构造函数的对象的成员函数处启动
std::thread
。 The standard way of starting a thread at a member function (see for example 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 ), but no luck. 我以为我可以通过使用
std::ref
来解决此问题(例如, 通过引用传递的std :: thread调用复制构造函数 ),但是没有运气。
Here is my code. 这是我的代码。 Thread
t1
works, but not t2
. 线程
t1
有效,但t2
无效。 If I try to uncomment the two lines, it gives: 如果我尝试取消注释这两行,它将给出:
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.
How do I start the thread directly at print()
, without needing uselessFunction
? 我如何直接在
print()
启动线程,而不需要uselessFunction
?
Also, I'd like to understand the error better. 另外,我想更好地理解该错误。 Which "deleted function" is the compiler complaining about?
编译器抱怨哪个“删除的函数”?
#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
use std::invoke
to call the function. std::thread
使用std::invoke
调用该函数。 std::invoke
is smart enough to be able to take a pointer to an object and call a member function with it. std::invoke
非常聪明,能够获取指向对象的指针并使用该对象调用成员函数。 That means you can change t2
to 这意味着您可以将
t2
更改为
std::thread t2(&Dummy::print, &d);
and get the correct behavior. 并获得正确的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.