相关疑难解决方法(0)

为什么将对象引用参数传递给线程函数无法编译?

我使用新的c ++ 11 std::thread接口遇到了问题.
我无法弄清楚如何std::ostream将对a的引用传递给线程将执行的函数.

这是传递整数的示例(在gcc 4.6下按预期编译和工作):

void foo(int &i) {
    /** do something with i **/
    std::cout << i << std::endl;
}

int k = 10;
std::thread t(foo, k);
Run Code Online (Sandbox Code Playgroud)

但是当我尝试传递一个ostream时,它无法编译:

void foo(std::ostream &os) {
    /** do something with os **/
    os << "This should be printed to os" << std::endl;
}

std::thread t(foo, std::cout);
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点,还是根本不可能?

注意:从编译错误看来它似乎来自一个已删除的构造函数...

c++ libstdc++ c++11

29
推荐指数
1
解决办法
2万
查看次数

std :: unique_ptr作为std :: thread中的函数参数

所以我试图将std::unique_ptr一个参数传递给一个在一个单独的线程中启动的函数,我在编译时得到一个奇怪的错误:

1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\functional(1149): error C2280: 'std::unique_ptr<Widget,std::default_delete<_Ty>>::unique_ptr(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)' : attempting to reference a deleted function
Run Code Online (Sandbox Code Playgroud)

此代码的简化版仍然会重现相同的问题:

#include <thread>
#include <memory>
#include <iostream>

class Widget
{
public:
  Widget() : m_data(0)
  {
  }

  void prepareData(int i)
  {
    m_data = i;
  }

  int getData() const
  {
    return m_data;
  }

private:
  int m_data;
};

void processWidget(std::unique_ptr<Widget> widget)
{
  std::cout << widget->getData() << std::endl;
}

int main()
{
  std::unique_ptr<Widget> widget(new Widget());
  widget->prepareData(42);

  std::thread t(processWidget, std::move(widget));
  t.join();

  return 0;
} …
Run Code Online (Sandbox Code Playgroud)

c++ multithreading unique-ptr visual-studio c++11

9
推荐指数
1
解决办法
1568
查看次数