Reputation:
I have a class Handler:
class Handler {
private:
std::mutex _mutex_list[4];
std:list<Person*> _waiting_list[4];
std::thread __runner_t;
public:
virtual void start();
};
I am trying to start the handler in a new thread:
Handler* handler = new Handler();
std::thread(&Handler::start, handler);
The problem is that apparently std::thread needs the class's transfer constructor, which I am unable to define as default because std::mutex can't be copied.
I defined a custom copy constructor which copies only the list but re-initializes the mutex array and thread.
Here it is:
Handler(const Handler& other) :
_mutex_list(), _waiting_list(other._waiting_list), _runner_t() {};
Doesn't work of course because the compiler asks for a transfer constructor.
I am not sure how to achieve the same for a transfer.
Is it a correct solution ? Is there a better solution ?
Help is appreciated.
Upvotes: 0
Views: 113
Reputation: 62603
There is no transfer
constructor, there is move constructor. Your code has a logical issue - you are creating a thread and you are copying your object into it, but this object owns the thread, which is just wrong.
I'd say, if you have an object which owns thread, running this thread should be it's own function, like:
class Handler {
...
void start() {
__runner_t = std::thread(&thread_func, this);
}
};
The technical compilation errors you are having, while solvable, highlight the logical issues.
Upvotes: 1