C++中的作用域终结函数

取自 A Tour of C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <cstdlib>
template <typename F>
struct Final_action {
explicit Final_action(F f) : act(f) { }
~Final_action() { act(); }
F act;
};

template <typename F>
[[nodiscard]] auto finally(F f) {
return Final_action{f};
}

void old_style(int n) {
void *p = malloc(n * sizeof(int));
auto act = finally([&]{ free(p); });
}

[[nodiscard]]确保必须保存函数调用的返回值,这样在act离开作用域的时候会自动调用析构函数,从而避免了在所有的出口处都手动写一堆清理代码,相比于goto bad也优雅不少