Improving Code Safety in C++26: Managers and Dangling References -- Bartlomiej Filipek

codesafety2-filipek.pngIn this blog post, we’ll explore ways to improve the safety of a simple configuration manager. We’ll handle common pitfalls like dangling references and excessive stack usage. Additionally, we’ll see how C++26 helps enforce safer coding practices with stricter diagnostics and improved handling of large objects.

Improving Code Safety in C++26: Managers and Dangling References

by Bartlomiej Filipek

From the article:

Step 1: The Buggy Implementation 
 
Below is a simple example of a manager object that stores various configs in a map and provides a method to retrieve them. When a requested configuration isn’t found, the code attempts to return a default certificate:

codesafety-filipek.png

Do you see a potential error in this code?

. . .

At first glance, the code looks harmless. However, if the requested entry isn’t found, the function returns a reference to a temporary std::vector. Once the function exits, that temporary is destroyed—leaving you with a dangling reference and undefined behavior.

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.