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: 
You should call `detach` if you're not going to wait for the thread to complete with `join` but the thread instead will just keep running until it's done and then terminate without having the spawner thread waiting for it specifically; e.g.

```
std::thread(func).detach(); // It's done when it's done

```

`detach` basically will release the resources needed to be able to implement `join`.

It is a fatal error if a thread object ends its life and neither `join` nor `detach` has been called; in this case `terminate` is invoked.
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.