Prominent C++ developer Herb Sutter has proposed eliminating many dangling and null reference bugs in C++, to to address a longstanding issue with the language and promote code safety.
The Version 1.0 proposal, which follows up the Version 0.9 of the plan from 2015, could become part of the C++ standard, although the initial intention is for it to serve as an informational contribution, said Sutter, who is chairman of the ISO C++ standards committee.
It would impact raw C-style pointers as well as references, iterators,
string_views, spans, and other nonowning types referring to data owned by someone else. Entitled, “Lifetime Safety: Preventing Common Danglng,” the proposal is intended to diagnose common cases of dangling in C++ code and report them as deterministic, readable errors at compile time. The proposal’s abstract describes the effort as a grand but speculative attempt to solve a 40-year-old problem.
The prescribed approach is identifying variables of generalized owner types, such as smart pointers and containers, and pointe” types, such as
span. Developers would then use a local, simple acyclic control graph to track pointers and identify when modifying an owner invalidates a pointer. This analysis takes advantage of C++ notions of scopes, object lifetimes, and
const that carry rich information available in reasonable modern C++ code. With minor extension, it appears this analysis also could detect uses of local moved-from variables, which are a form of dangling.
Warnings can be implemented to give consistent results across implementations, which has been validated by partial implementations in Clang and MSVC, and be efficient enough to run during regular compilation. The Clang implementation is unoptimized and performs extra work but still incurs fewer than 10 percent overhead in compiling large LLVM translation units.
Sutter admits that this attempt to solve the dangling issue could fail. But much of the value of the work could be realized if dangling detection could become de facto implemented in C++ compilers, if not formally standardized, he said. If implemented de facto, compilers could reliably diagnose these problems as common vendor extensions. That would eliminate or at least improve C++’s reputation for being a “breeding ground” for dangling pointers, iterators,
string_views, and more.
Alternative proposals to address this proposal advocate for formal standardization of widespread annotations in the language and standard library covered by the work in the dangling proposal.