Boost threads - passing parameters by reference

MistyD picture MistyD · Jun 20, 2013 · Viewed 7.1k times · Source

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.

Answer

Igor R. picture Igor R. · Jun 20, 2013

Bind copies its parameters. Use boost::ref:

boost::thread t(boost::bind(&SomeClass::OtherMethod,this, boost::ref(v))