Search code examples
c++multithreadingc++11stdstdthread

Delete std::thread after calling join?


I have some code that dynamically allocates a new std::thread from the C++11 <thread> header, like this:

std::thread *th = new thread( /* my args */);

Some time later, I call join:

th->join();

Since I dynamically allocated the thread, do I also need to call delete th; to free the memory? If I do, do I still need to call join() first?


Solution

  • 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.