3

我的应用程序有一个类似于以下代码的部分

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
}

我想知道为什么在堆栈上创建向量时向量 v 为空,而在堆上创建向量时它工作。我期待上面的代码能够工作,因为即使在堆栈上创建向量,它仍然在范围内。

4

2 回答 2

10

Bind复制其参数。使用boost::ref

boost::thread t(boost::bind(&SomeClass::OtherMethod,this, boost::ref(v))
于 2013-06-20T17:02:05.587 回答
0

默认情况下,线程按值接受参数,即使函数本身需要引用。使用 boost::ref() 强制通过引用传递参数。

() 默认情况下,参数被复制到内部存储中,新创建的执行线程可以在其中访问它们,即使函数中的相应参数需要引用。

A. Williams,“Concurrency in Action”,2.2 将参数传递给线程函数。

于 2013-10-08T04:46:33.030 回答