Passing class object into thread

时间:2018-01-15 18:12:11

标签: c++ multithreading

void thread_func(Color& r)
{
   //
}

void f()
{
   Color r(red_state);
   thread t(thread_func, r);
   t.join();
}

Simplified. I can't find anything online that matches this specific case (class object passed into non-member thread function). I've tried a few suggestions (adding '&', std::ref(r), using vectors, etc.), but I keep getting the following errors:

error: no type named 'type' in 'class std::result_of<void (*(Color*))(Color&)>'
error: use of deleted function 'Color::Color(const Color&)'

The latter makes me think it has something to do with the copy constructor, but I figured passing it in by reference shouldn't affect that? Any tips or feedback would be greatly appreciated.

2 个答案:

答案 0 :(得分:2)

Use std::ref to pass by a reference. Namely:

thread t(thread_func, std::ref(r));

Learn about std::reference_wrapper to find out why: http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper.

答案 1 :(得分:1)

When you try passing your object to the function as an argument, you are trying to pass it by value. Doing so with complex object and not just primitives causes C++ to call the copy constructor in order to construct a new object which is a copy of the object you passed.

Doing so with reference will result the same thing, as you see it has tried to call Color::Color(const Color&), which, as noted, got deleted.

You can try passing Color* (a pointer to Color) which should work, but this means you are going to use the exact same object, which can be dangerous if you are not careful with using it from two different threads. each change you will make to the object on the first thread will also apply for the second.