An object's lifetime is the period during which it exists and can be validly accessed. A thread that outlives a local variable can access it after destruction, causing undefined behavior. section 2.1.1
Detaching a thread does not ensure it finishes before its launching function exits. Copying data into a self-contained thread function can avoid sharing local variables, but copied objects that contain pointers or references can still outlive their referents. section 2.1.1
Listing 2.1. A function that returns while a thread still has access to local variables
struct func
{
int& i;
func(int& i_):i(i_){}
void operator()()
{
for(unsigned j=0;j<1000000;++j)
{
do_something(i); #1
}
}
};
void oops()
{
int some_local_state=0;
func my_func(some_local_state);
std::thread my_thread(my_func);
my_thread.detach(); #2
} #3
A detached thread calls a function object holding a reference to a local integer; the function may continue using it after the launching function returns. section 2.1.1
