July 26th, 2024

Safer code in C++ with lifetime bounds

Daniel Lemire's blog emphasizes using lifetime bounds in C++ to improve code safety and performance, highlighting the role of std::string_view in avoiding unnecessary copies and preventing dangling references.

Read original articleLink Icon
Safer code in C++ with lifetime bounds

Daniel Lemire's blog discusses the use of lifetime bounds in C++ to enhance code safety and performance. The blog highlights the importance of avoiding unnecessary copies in software development, which can be achieved through the use of references or pointers, exemplified by the std::string_view class. This class allows developers to create a view of a string without owning the underlying memory, but it necessitates careful tracking of memory ownership to prevent dangling references.

Lemire points out that while modern tools can detect such bugs, it would be more efficient if compilers could provide immediate feedback. Some C++ compilers, including Visual Studio and LLVM, now support lifetime-bound annotations that help identify potential issues. He illustrates this with an example involving URL parsing, where returning a std::string_view from a temporary object can lead to unsafe code.

By annotating functions with lifetime-bound attributes, developers can receive compile-time warnings about potential dangling references. Although this feature is not yet perfect and may not always trigger warnings, it represents progress in catching errors early in the development process. Lemire credits Denis Yaroshevskiy for bringing this compiler feature to his attention and encourages further exploration of the LLVM documentation for more information.

Link Icon 4 comments
By @MaxBarraclough - 3 months
Presumably these issues could be detected at runtime by having the compiler add checking logic into dev/debug builds.

The static approach used here may have the advantage of giving a more categorical assurance, i.e. one that doesn't depend on the particular behaviour exercised at runtime, but it requires annotations, meaning that:

1. It can't be used on an existing codebase lacking these annotations

2. It trusts the programmer to get the annotations right

(I'm not particularly well informed of recent developments in C++, perhaps such runtime instrumentation already exists?)

By @wakawaka28 - 3 months
Does anyone actually want to clutter their code with such annotations? The example looks like something that should always warn or always generate an error, which makes this whole exercise seem that much worse.
By @jeffbee - 3 months
I am in favor of these kinds of annotations but in a recent clang I get this already, no annotations:

object backing the pointer will be destroyed at the end of the full-expression [-Werror,-Wdangling-gsl]

By @klyrs - 3 months
Gesundheit