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

pab*_*xrl 9 c++ multithreading unique-ptr visual-studio c++11

所以我试图将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)

我的猜测是Widget对象的破坏有main(问题,但我无法确定问题.是否有必要做一些额外的事情来清理那个变量?顺便说一下,我正在使用VS2013.

小智 -1

不允许复制 unique_ptr,因此复制构造函数被禁用。那是指向编译器错误。

您可以通过参考修复它:

void processWidget(std::unique_ptr<Widget>& widget)
Run Code Online (Sandbox Code Playgroud)

  • 没有人在OP的代码中复制 (4认同)