I want to start a std::thread
at a member function of an object that does not have a copy constructor. 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.
Here is my code. Thread t1
works, but not 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
?
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::invoke
is smart enough to be able to take a pointer to an object and call a member function with it. That means you can change t2
to
std::thread t2(&Dummy::print, &d);
and get the correct behavior.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.