Does C++ 11 thread automatically destroy after detach

You should consult a better reference. From std::thread::detach:

Separates the thread of execution from the thread object, allowing execution to continue independently. Any allocated resources will be freed once the thread exits.

After calling detach *this no longer owns any thread.

So to answer your questions (if they aren't already):

forever?

No. If the thread finishes (for example: if it counts to 10), it is done and it is not running anymore.

Does its resource remain forever?

No, when the thread finishes, every resource from the thread is freed (like variables and such).

It can be destroyed safely, but is it automatically?

What do you mean? When the thread is done, it is destroyed (automatically), regardless of whether you call detach or not. The only difference is that here, they are referring to the thread object, so the actual std::thread instance.

So when the thread object is destructed, you must have called join or detach regardless whether you own that the actual thread finished or not. If you don't, std::terminate is called.


A std::thread is just a thin wrapper around your platform's native threading library... It doesn't really contain much internally besides a few flags and the native handle to the platform's thread representation (which for both Unix & Windows is a fancy integral identifier). Speaking specifically of Unix-like systems, the call to std::thread::detach() does two things:

  • calls some variation of pthread_detach(), which frees a data structure used to store the returning void pointer from platform-native thread-main.
  • sets a flag in the class denoting that the thread has been detached, and that, in turn, prevents the destructor from throwing an exception.

As for any other resources that the thread creation may set up, those should be cleaned up by your platform's run-time when your thread-main exits.

So, putting it another way, std::thread::detach just allows the wrapper to be destroyed without throwing an exception; the actual thread's stack and OS resource reclamation happens in the thread's execution context after your thread's main function exits, and that should be 100% automatic.