线程多次调用析构函数

时间:2014-07-02 07:09:53

标签: c++ multithreading c++11 destructor

我是c ++ 11中std::thread的新手。我尝试将functor-object传递给线程而不是lambda

然而,输出让我感到惊讶:似乎析构函数被调用了6次。

代码段:

#include <iostream>
#include <thread>

struct A
{
  A()
  { 
    std::cout << "creating A" << std::endl; 
  }

  void operator()()
  {
    std::cout << "calling ()-operator" << std::endl;
  }

  ~A()
  { 
    std::cout << "destroying A" << std::endl;   
  }
};

int main()
{
  {
    std::thread t( (A()) );
    t.join();
  }
  std::cin.get();
}

我得到的输出(msvc11)是

creating A
calling ()-operator
destroying A
destroying A
destroying A
destroying A
destroying A
destroying A

非常感谢任何解释。!

1 个答案:

答案 0 :(得分:2)

您无法捕获可以创建对象的所有路径。将复制构造函数添加到A

A( A const &a )
{
    std::cout << "creating A (copy)" << std::endl;
}