nick huang
nick huang

Reputation: 463

why thread function's param is a ref, the complier failed?

i feel confused about the ref as parameters when using thread library, below is the code:

#include "../include.h"  // include some header file
class A { 
 public:
  A(unordered_map<int, int>& m) : m(m) {  
  }
  void Start() {
    std::thread(test1, m); 
  }
 private:
  static void test1(unordered_map<int, int>&  m) {  // complie failed, if the ref change to value(remove &), it's ok, thats confused me
    for (auto i : m) {
      cout << i.first << i.second << endl;
    }   
  }
  unordered_map<int, int> & m;
};

int main() {
  unordered_map<int, int> m = {{1,2}, {3,4}};
  A a(m);
  a.Start();
}

when i let test1's params be ref, it failed, and come out a lot of msg:

In file included from /usr/include/c++/4.8.2/thread:39:0,
                 from ./../include.h:6,
                 from ./[email protected]:1:
/usr/include/c++/4.8.2/functional: In instantiation of ‘struct std::_Bind_simple<void (*(std::unordered_map<int, int>))(std::unordered_map<int, int>&)>’:
/usr/include/c++/4.8.2/thread:137:47:   required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (&)(std::unordered_map<int, int>&); _Args = {std::unordered_map<int, int, std::hash<int>, std::equal_to<int>, std::allocator<std::pair<const int, int> > >&}]’
./[email protected]:10:25:   required from here
/usr/include/c++/4.8.2/functional:1697:61: error: no type named ‘type’ in ‘class std::result_of<void (*(std::unordered_map<int, int>))(std::unordered_map<int, int>&)>’
       typedef typename result_of<_Callable(_Args...)>::type result_type;
                                                             ^
/usr/include/c++/4.8.2/functional:1727:9: error: no type named ‘type’ in ‘class std::result_of<void (*(std::unordered_map<int, int>))(std::unordered_map<int, int>&)>’
         _M_invoke(_Index_tuple<_Indices...>)
         ^

but good if the params be value, i dont know the difference, can anyone help on this?

Is there any special things i dont know about the thread function parameters? Thanks a lot.

Upvotes: 0

Views: 43

Answers (1)

rmawatson
rmawatson

Reputation: 1935

From cppreference,

The arguments to the thread function are moved or copied by value. If a reference argument needs to be passed to the thread function, it has to be wrapped (e.g. with std::ref or std::cref).

So,

  void Start() {
    auto t = std::thread(test1, std::ref(m)); 
    t.join(); // so it waits for the thread to finish printing for your example.
  }

Demo

Upvotes: 2

Related Questions