0%

scope guard cpp b版的defer

scope guard cpp 版的defer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
template <class Function>
class ScopeGuard {
private:
Function m_func;
bool m_dismiss{false};

public:
explicit ScopeGuard(Function func) : m_func(func), m_dismiss(false) {}
~ScopeGuard() {
if (!m_dismiss) m_func();
}
ScopeGuard() = delete;
ScopeGuard(const ScopeGuard&) = delete;
ScopeGuard& operator=(const ScopeGuard&) = delete;

void dismiss() { m_dismiss = true; }

ScopeGuard(ScopeGuard&& rhs) : m_func(std::move(rhs.m_func)), m_dismiss(rhs.m_dismiss) { rhs.dismiss(); }
};
template <class Fun>
ScopeGuard<Fun> MakeScopeGuard(Fun f) {
return ScopeGuard<Fun>(std::move(f));
}
  • 类似go的defer,java的finally,离开作用域时执行注册的代码
  • 再也不用忘记资源回收了^v^