Delete std::thread after calling join? Delete std::thread after calling join? multithreading multithreading

Delete std::thread after calling join?


To avoid memory leaks, you need to both: join a running thread, and make sure it is destructed/deleted (let it go out of scope for stack-allocated std::threads or explicitly call delete for std::thread*).

See thread::~thread in cppreference:

A thread object does not have an associated thread (and is safe to destroy) after:

  • it was default-constructed
  • it was moved from
  • join() has been called
  • detach() has been called

A non-joined thread, therefore, cannot be safely destructed.

A join()ed std::thread will still occupy some memory. Therefore you need to make sure it is properly deallocated if it is on the heap.


Yes you have to call join before destroying the thread object. If the destructor for a std::thread object that is joinable (i.e. if joinable returns true) is called, it will call std::terminate. Therefore, you have to call join before destroying the thread, whether by calling delete (for threads on the heap) or by it being destroyed normally.

To prevent a memory leak you have to call delete, as with any other heap allocated variable.

See here for more information on std::thread.