Sometimes some object A needs to interact with another object B, e.g., A calls one of B’s methods. In a memory-unsafe language like C++, it is left to the programmer to assure that B outlives A; if B happens to be already destructed, this would be a use-after-free bug. Managing object lifetimes can be tricky, especially with asynchronous code. Perhaps unneeded, but here is a simple example of the problem: struct Foo { void foo(); }; struct Bar { Foo* f; void call_foo() { f->foo(); } }; int main(){ Bar A; { Foo B; A.f = &B; } // B destructed A.call_foo(); // Oops return 0; } You could of course argue that one should use a more modern, memory-safe language such as Rust to rule out such bugs by construction. But sunken cost in an existing codebase, or the more mature library ecosystem of an older language like C++ can easily render such a rewrite economically infeasible. By the way, (and please correct me in case my understanding here is incorrect as a very inexperienced Rust programmer), getting Rust’s borrow checker to understand and agree with object lifetimes in your asynchronous code without having to sprinkle 'static in many places can vary from challenging to currently impossible. Also, C++ compilers are improving, so by enabling all warnings and by using features like Clang’s lifetimebound attribute you will already catch trivial instances like the one above, but there is currently no guarantee that more opaque instances of the same bug pattern, possibly spread over multiple translation units, will be caught by the compiler. One way to avoid lifetime problems like the one sketched above in C++ (at least C++11, that is) is for A to manage the lifetime of B, say via a std::unique_ptr or std::shared_ptr. struct BarOwnsFoo { std::unique_ptr<Foo> f; void call_foo() { f->foo(); } }; int main(){ BarOwnsFoo A; { auto B_ptr = std::make_unique<Foo>(); A.f = std::move(B_ptr); } // B kept alive inside A A.call_foo(); // Okay return 0; } Safe interactions between separately...
First seen: 2025-09-28 19:29
Last seen: 2025-09-29 02:30