An (In-)Complete Guide to C++ Object Lifetimes

Jonathan Müller

60
advanced
11:00-12:30, Thursday, 4th July 2024

A C++ program manipulate objects, but it is undefined behavior if you attempt to manipulate them while they are not alive. So let's do a deep dive into object lifetime.

When are objects created and when are they destroyed? How does temporary lifetime extension come into play and what changed there recently? What happens when you std::malloc memory and just pretend objects are there without creating anything? Or worse: You use mmap() to read shared memory. How do unions interact with constructors, strict aliasing, or the "common initial sequence"? What when you explicitly call the destructor and later re-use the same storage? What's the deal with std::launder, std::bit_cast, and std::start_lifetime_as?

We'll answer all of those questions and much more. We'll do that by looking at the C++ standard, old and new proposals, and compiler optimizations.

undefined behavior
objects
lifetime
standard

Jonathan Müller

Jonathan is a Software Engineer at think-cell where he maintains the core libraries. He is the author of C++ open source projects like type_safe, a library of safety utilities and foonathan/memory, a memory allocator library. More recently, he’s taken an interest in programming languages and compilers and has published lexy, a parser library, and lauf, a bytecode interpreter. He is also on the C++ standardization committee where he is the assistant chair for std::ranges.