c++ - std::unique_ptr 作为在 std::thread 中运行的参数

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

<分区>

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

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

#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;
}

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

最佳答案

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

您可以通过引用修复它:

void processWidget(std::unique_ptr<Widget>& widget)

关于c++ - std::unique_ptr 作为在 std::thread 中运行的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33870414/

相关文章:

c++ - 类中成员声明顺序如果相互依赖,最优解

c++ - 实现二叉树遍历时的核心转储

java - 强制执行打印顺序,但线程在一次迭代后彼此等待

c# - 成员定义了不止一次的错误信息?

c++ - 语句初始化属于哪一类?

java - 从java中的另一个线程访问一个线程的变量

java - 执行者服务 - 线程超时

c# - 是否可以通过 Visual Studio Code 创建 Windows 服务?

visual-studio - 签名者的证书对于签名无效

c++ - unordered_map Vs map Vs数组-内存分析