C++ Uses Destructors Instead of try...finally for Cleanup Code
By
ibobev
Crispy enough to crunch, soft enough to enjoy. A good bake.
Summary
The article explains how C++ handles cleanup code differently from other programming languages that have try...finally constructs. While languages like Java, C#, Python, and JavaScript use try...finally blocks to ensure code executes when control leaves a block, C++ uses destructors for this purpose. The article specifically mentions the Windows Implementation Library's wil::scope_exit function, which leverages C++'s destructor mechanism to execute cleanup code, effectively serving as C++'s version of finally blocks.
Key quotes
· 5 pulledMany languages that have exceptions also have a finally clause, so you can write try { ⟦ stuff ⟧ } finally { always(); }
C++ says, 'We have try…finally at home.'
In C++, the way to get a block of code to execute when control leaves a block is to put it in a destructor, because destructors run when control leaves a block.
This is the trick used by the Windows Implementation Library's wil::scope_exit function: The lambda you provide is placed inside a c
The destructor serves as the 'finally'.
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
Bjarne Stroustrup on Safe C++: RAII vs Manual Resource Management
The article discusses Bjarne Stroustrup's presentation on Safe C++ programming, focusing on resource management pitfalls in C code and the R
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
