title: C++ thread delete itself at its end
body: <p>I am writing a server with allow connection from multiple client in same time. I create a new thread for every new connection. The client communicate with the server with this thread. I need to unallocate the memory for the thread into the server process when the client disconnect from the server.</p>
  
  <p>The problem is when I try to "delete the thread itself". </p>
  
  <p>I write a little code to explain my problem. The Class C represent a new connection. I create a new object of this class dynamically for every connection. The function action is voluntarily simplified to explain the problem.</p>
  
  <pre><code>#include &lt;thread&gt;
  #include &lt;iostream&gt;
  #include &lt;mutex&gt;
  #include &lt;chrono&gt;
  
  using namespace std;
  
  mutex m;
  
  class C {
    thread *t;
  
    static void action(int n, C* obj) {
      for (int i = 0; i &lt; 10; i++) {
        m.lock();
        cout &lt;&lt; "i:" &lt;&lt; i &lt;&lt; ", n:" &lt;&lt; n &lt;&lt; endl;
        m.unlock();
      }
      delete(obj);
    }
  
    public:
      C() : t(nullptr) {}
  
      ~C() {
        delete(t); // Work if I comment this line
      }
  
      void launch() {
        static int i = 0;
        t = new thread(action, i++, this);
      }
  
  };
  
  int main() {
    C *c1 = new C();
    c1-&gt;launch();
  
    this_thread::sleep_for(chrono::seconds(5));
    return 0;
  }
  </code></pre>
  
  <p>Sorry for my English I am learning it.</p>