use*_*014 1 c++ unique-ptr c++11
我想使用std::unique_ptr的删除器来保证一些代码会在离开作用域时执行。例如,假设我有一个Event带有 function的类set_event()。
我想确保在离开范围时,my_event.set_event()将调用该函数。我设法得到了类似的东西:
Event my_event;
auto releasing_function = [&my_event] (void*){my_event.set_event();};
std::unique_ptr<void, decltype(releasing_function)> safe_event((void*)1, releasing_function);
Run Code Online (Sandbox Code Playgroud)
但我觉得我们可以做得更好。也许是一个没有这个自动 lambda 函数的单行,或者避免这个丑陋的(void*)1. 甚至可能完全删除unique_ptr。
编辑:我想避免实用程序类。这太容易了:)
在一些标题中定义一个 maker-function 以方便使用:
template<class F> auto scope_guard(F&& f) {
return std::unique_ptr<void, std::decay<F>::type>{(void*)1, std::forward<F>(f)};
}
Run Code Online (Sandbox Code Playgroud)
并像这样使用它:
auto unique = scope_guard([&]{/* cleanup here */});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
605 次 |
| 最近记录: |