Search code examples
c++multithreadingc++11stdthread

Does a detached std::thread need to be deleted after it terminates?


I create a new std::thread object, and then detach() it. The thread runs for an arbitrary amount of time, and then terminates itself. Since I created the object with new, do I need to delete it at some point to free up its resources? Or does the thread effectively delete itself upon termination?

If it does effectively delete itself, will something bad happen if I explicitly delete it after it has terminated?


Solution

  • Yes, you have to delete it by yourself.

    Once you called std::thread::detach, the thread will be separated from the thread object and allowed execution to continue independently, and then the thread object will no longer owns any thread. So the thread won't and impossible to delete it upon termination.