Bjarne Stroustrup on Safe C++: RAII vs Manual Resource Management
By
signa11
Crackling crust, pillowy middle. The kind of bagel that earns a second cup of coffee.
Summary
The article discusses Bjarne Stroustrup's presentation on Safe C++ programming, focusing on resource management pitfalls in C code and the RAII (Resource Acquisition Is Initialization) pattern in C++ as a solution. It analyzes a specific example where a file handle can leak if cleanup is missed, contrasts this with C++'s RAII approach using destructors for automatic cleanup, and explores broader implications for safe programming practices and language design.
Key quotes
· 5 pulledvoid f(const char* p) { FILE *f = fopen(p, "r"); // use f fclose(f); }
class File_handle { FILE *p; public: File_handle(const char *pp, const char *r) { p = fopen(pp, r); } ~File_handle() { fclose(p); } };
Any code that exits the function inside // use f that doesn't also call fclose results in a leak.
He shows this code to demonstrate how easy it is to miss resource cleanup.
He provides a C++ equivalent with RAII to avoid this footgun.
You might also wanna read
Optimizing C++ Singleton Performance: Best Practices and Implementation Guidance
This article focuses on optimizing C++ singleton implementations for performance, using a display manager example from the Linux world (like
C++26's std::is_within_lifetime: Checking Object Lifetime During Constant Evaluation
The article explains C++26's new std::is_within_lifetime function, which checks whether a pointer points to an object within its lifetime du
Implementing an Efficient uint128 Type in Modern C++ for x64 Architecture
This article provides a practical guide to implementing an efficient 128-bit unsigned integer (uint128) type in modern C++. The author focus
C++ Uses Destructors Instead of try...finally for Cleanup Code
The article explains how C++ handles cleanup code differently from other programming languages that have try...finally constructs. While lan
C++20 Coroutines Tutorial: Practical Guide to Asynchronous Programming
This article is a comprehensive tutorial on C++20 coroutines, written by an experienced C++ developer with 25 years of event-driven programm
Compact C++ String Formatting Library Implementation in 65 Lines
A technical article presenting a compact string formatting library implementation in C++ that uses only 65 lines of code. The library was de
