Implementation:ClickHouse ClickHouse Scope Guard
Appearance
| Knowledge Sources | |
|---|---|
| Domains | Resource_Management, Patterns |
| Last Updated | 2026-02-08 00:00 GMT |
Overview
RAII-based scope guard for automatic cleanup actions when leaving a scope.
Description
Executes a function on destruction, providing exception-safe cleanup. Supports move semantics, joining multiple guards, and manual reset.
Usage
Use for ensuring cleanup code runs (closing files, unlocking mutexes, rolling back transactions), especially in exception paths.
Code Reference
Source Location
- Repository: ClickHouse
- File: base/base/scope_guard.h
- Lines: 1-116
Signature
template <class F>
class BasicScopeGuard {
public:
constexpr BasicScopeGuard(F && function_);
~BasicScopeGuard();
void reset();
F release();
};
using scope_guard = BasicScopeGuard<std::function<void(void)>>;
template <class F>
inline BasicScopeGuard<F> make_scope_guard(F && function_);
#define SCOPE_EXIT(...) /* ... */
Import
#include <base/scope_guard.h>
Usage Examples
#include <base/scope_guard.h>
void process() {
FILE* f = fopen("file.txt", "r");
SCOPE_EXIT({ if (f) fclose(f); });
// File guaranteed to close on any exit path
}
// Manual scope guard
auto guard = make_scope_guard([&]() {
cleanup_resources();
});
// Release guard if cleanup not needed
if (success)
guard.release();
Related Pages
Page Connections
Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment