liveBook · Manning

Object lifetime

As explained in C++ Concurrency in Action, Second Edition

An object's lifetime is the period during which the C++ object exists and may be validly accessed.

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

How C++ Concurrency in Action, Second Edition covers it

How deep it goes
Works through a detached-thread example and suggests copying data or ensuring the thread finishes before function exit.
Examples
Uses a detached thread whose function object references a local integer after its launching function returns.
What you can do after
Diagnose when a thread might access a local variable after its destruction and avoid the risk by copying data or ensuring completion.
How it connects
Connects object lifetime to threads, detachment, references, and undefined behavior.

This explainer was generated by Manning's knowledge graph from the text of C++ Concurrency in Action, Second Edition. The section links point to the parts of the book it draws on.