title: In C++, can I create a thread and save it as a class member variable so it can be joined automatically in the destructor?
body: <p>I have a c++ program in which I want to be able to call a member function which will start a separate thread. When I detach the thread, it works fine, but then I have no way to join it, so I want to store the thread as a member variable and join it automatically in the destructor.</p>
  <p>I thought that's what the following code would do, however, I get the output shown below instead, which leads me to believe the thread is never joined. How do I join a thread saved as a member variable with a member function?</p>
  <p>Please advise!</p>
  <pre><code>// thread example
  #include &lt;iostream&gt;       // std::cout
  #include &lt;thread&gt;         // std::thread
  #include &lt;windows.h&gt;
  
  using namespace std;
  
  void foo(int i) 
  {
      while(true){
          cout &lt;&lt; &quot;Foo checkin&quot; &lt;&lt; endl;
          Sleep(3000);
      }
  }
  
  class ThreadHolder{
      public:
          ThreadHolder(int in){i = in;};
          int i;
          void start_threads(){
              t = thread(foo, i);     // spawn new thread that calls foo()
  
              std::cout &lt;&lt; &quot;foo started\n&quot;;
              return;
          }
          ~ThreadHolder();
      private:
          thread t;
  };
  
  ThreadHolder::~ThreadHolder(){
      if (t.joinable()){
          cout &lt;&lt; &quot;in dest\n&quot;;
          t.join();
          cout &lt;&lt; &quot;joined\n&quot;;
      }
  }
  
  
  
  int main() 
  {
      cout &lt;&lt; &quot;in main&quot; &lt;&lt; endl;
      ThreadHolder th(1);
      th.start_threads();
      cout &lt;&lt; &quot;back in main&quot; &lt;&lt; endl;
      return 0;
  }
  </code></pre>
  <p>OUTPUT:</p>
  <pre><code>in main
  foo started
  back in main
  in dest
  Foo checkin
  Foo checkin
  Foo checkin
  Foo checkin
  Foo checkin
  Foo checkin
  </code></pre>