Scope guards are a programming construct that helps ensure cleanup or resource management in the presence of exceptions or early returns. They are particularly useful in languages that do not have built-in support for RAII (Resource Acquisition Is Initialization), like C++. By utilizing scope guards, you can define cleanup actions that get executed when a block of code is exited, helping to manage resource leaks and maintain cleaner code.
#include
#include
class ScopeGuard {
public:
explicit ScopeGuard(std::function onExit) : onExit_(onExit), dismissed_(false) {}
~ScopeGuard() {
if (!dismissed_) {
onExit_();
}
}
void dismiss() {
dismissed_ = true;
}
private:
std::function onExit_;
bool dismissed_;
};
void exampleFunction() {
ScopeGuard guard([] {
std::cout << "Cleanup action executed!" << std::endl;
});
std::cout << "Doing some work..." << std::endl;
// Simulate some logic
if (true) {
// Early return or exit
return;
}
// If we reach here, cleanup will not happen
guard.dismiss();
}
int main() {
exampleFunction();
return 0;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?