#lifetime
7 posts tagged #lifetime.
A stdexec task next to a generator (a reference implementation, not std::execution::task)
exec::task from NVIDIA's stdexec library, not the standard's std::execution::task, builds and runs on GCC 16.2 and Clang trunk. One task costs 1 allocation of 168 to 176 bytes, a task awaiting two tasks 3. A const& parameter dangles in a task as in a generator.
Clang 23.1 -Wlifetime-safety warns on 6 of 7 dangling cases, GCC 16.2 on 1
On seven small dangling cases, Clang 23.1 with -Wlifetime-safety warns on six. GCC 16.2 with -Wall -Wextra -Wdangling-pointer=2 -Wdangling-reference gives a correct dangling report on one, from inside a standard header. Without the flag Clang already warned on three. The flag adds an escaping lambda capture, a reference across push_back and a view field set from a parameter, and it flags one correct program. Trunk renamed the push_back check.
When a std::generator const& argument outlives the call, by compiler
A coroutine that takes const& and is called with a temporary in a range-for is safe on GCC 15.1 and Clang 19.1 or later, and dangles on GCC 14.2 and on MSVC 19.51. Storing the generator first dangles on every compiler I ran. No compiler warned. A reflection check of under 50 lines flags the signature on GCC 16.2.
A thread that starts before its counter exists
A std::jthread member declared before the data it uses breaks at both ends of the object's life. ThreadSanitizer reports the construction end, exit 66, on GCC 16.2 and clang trunk. The destruction end is silent for an atomic and reported for a vector. GCC 16.2 -Wall -Wextra -Weffc++ and clang trunk -Weverything say nothing about the order.
Reflection can flag a dangling signature that GCC 16.2 does not warn about
A reflection lint of under 60 lines flags 3 of 5 declarations in a namespace on GCC 16.2: two return a view of a by-value owner, one returns a reference that can bind a temporary. For the view case GCC 16.2 gives no warning with -Wall -Wextra, a plain run prints garbage, and AddressSanitizer reports a heap use after free.
The pmr crash is the buffer that died first
The most common pmr crash rarely comes from a custom resource; it is lifetime. The container deallocates back into its resource on destruction, so the resource must outlive it. A live demo shows the destruction order and the declaration-order rule that keeps it correct. Episode 6 of the pmr series.
Clang's lifetimebound warns about a copy, and that is the problem
The lifetimebound attribute lets -Wdangling see through a function call, which is how clang catches a string_view into a temporary. It has no conditional form, so a function that returns a copy on some instantiations and a reference on others has to pick between missing real dangles and warning about correct code. A proposal on the LLVM forum wants to close that gap.