4

My application has a section that resembles the following code

void SomeClass::OtherMethod(std::vector<std::string>& g)
{
  g.pushback("Something");
}

void SomeClass::SomeMethod()
{
  std::vector<std::string> v;
  boost::thread t(boost::bind(&SomeClass::OtherMethod,this,v)
  t.join();
  std::cout << v[0]; //Why is this empty when the vector created on stack
}

I wanted to know why the vector v is empty when the vector is created on the stack and it works when it is created on the heap. I was expecting the above code to work since the vector remains in scope even when it is created on the stack.

Igor R.
  • 14,716
  • 2
  • 49
  • 83
MistyD
  • 16,373
  • 40
  • 138
  • 240

2 Answers2

11

Bind copies its parameters. Use boost::ref:

boost::thread t(boost::bind(&SomeClass::OtherMethod,this, boost::ref(v))
Igor R.
  • 14,716
  • 2
  • 49
  • 83
  • Thanks for your reply. However I still dont get it. If bind copies its parameter how does that make a difference. Sorry I am confused here – MistyD Jun 20 '13 at 17:05
  • @MistyD Now it copies a `reference_wrapper`, which takes its argument (i.e. your vector) by reference and provides implicit `T&` type-cast operator. – Igor R. Jun 20 '13 at 17:08
  • I understand that `boost::ref` will do the trick. I am just curious why it doesnt work without it. You stated that without using boost::ref it will make a copy. I am just curious about the fact that even if it makes a copy why doesnt it work ? – MistyD Jun 20 '13 at 17:09
  • @MistyD Because `OtherMethod` takes by reference a *copy* of the original vector and changes it. The original vector remains unchanged. – Igor R. Jun 20 '13 at 17:12
0

A thread by default takes arguments by value, even if the function itself expects a reference. Use boost::ref() to force passing argument by reference.

() by default the arguments are copied into internal storage, where they can be accessed by the newly created thread of execution, even if the corresponding parameter in the function is expecting a reference.

A. Williams, "Concurrency in Action", 2.2 Passing arguments to a thread function.

cpp
  • 3,743
  • 3
  • 24
  • 38