All Topics
All Topics
Technology
Technology
Design
Design
Programming
Programming
Science
Science
News
News
Gaming
Gaming
Entertainment
Entertainment
Business
Business
Finance
Finance
Sports
Sports
Health
Health
Food
Food
Travel
Travel
Art
Art
Music
Music
Books
Books
Education
Education
Politics
Politics
Personal
Personal
No algorithm. No AI slop. No ads. Just RSS. Pro-human. Indie writers. Real journalism. Open web. Chronological. Hand toasted.

C++ Uses Destructors Instead of try...finally for Cleanup Code

By

ibobev

5mo ago· 3 min readenInsight

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 pulled
Many 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'.
Snippet from the RSS feed
The destructor serves as the "finally".

You might also wanna read