Question: Sometime I have to use `std::thread` to speed up my application. I also know `join()` waits until a thread completes. This is easy to understand, but what's the difference between calling `detach()` and not calling it?

I thought that without `detach()`, the thread's method will work using a thread independently.

Not detaching:

```
void Someclass::Somefunction() {
    //...

    std::thread t([ ] {
        printf("thread called without detach");
    });

    //some code here
}

```

Calling with detaching:

```
void Someclass::Somefunction() {
    //...

    std::thread t([ ] {
        printf("thread called with detach");
    });

    t.detach();

    //some code here
}

```

Answer: 
This answer is aimed at answering question in the title, rather than explaining the difference between `join` and `detach`. So when should `std::thread::detach` be used?

In properly maintained C++ code `std::thread::detach` should not be used at all. Programmer must ensure that all the created threads gracefully exit releasing all the acquired resources and performing other necessary cleanup actions. This implies that giving up ownership of threads by invoking `detach` is not an option and therefore `join` should be used in all scenarios.

However some applications rely on old and often not well designed and supported APIs that may contain indefinitely blocking functions. Moving invocations of these functions into a dedicated thread to avoid blocking other stuff is a common practice. There is no way to make such a thread to exit gracefully so use of `join` will just lead to primary thread blocking. That's a situation when using `detach` would be a less evil alternative to, say, allocating `thread` object with dynamic storage duration and then purposely leaking it.

```
#include <LegacyApi.hpp>
#include <thread>

auto LegacyApiThreadEntry(void)
{
    auto result{NastyBlockingFunction()};
    // do something...
}

int main()
{
    ::std::thread legacy_api_thread{&LegacyApiThreadEntry};
    // do something...
    legacy_api_thread.detach();
    return 0;
}

```
According to [cppreference.com](https://en.cppreference.com/w/cpp/thread/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.
> 
> 
> 

For example:

```
  std::thread my_thread([&](){XXXX});
  my_thread.detach();

```

Notice the local variable: `my_thread`, while the lifetime of `my_thread` is over, the destructor of `std::thread` will be called, and `std::terminate()` will be called within the destructor.

But if you use `detach()`, you should not use `my_thread` anymore, even if the lifetime of `my_thread` is over, nothing will happen to the new thread.