scopeguard.h (1405B)
1 /* 2 * Copyright (C) 2019 Daniel Vrátil <dvratil@kde.org> 3 * 2021 Willy Goiffon <contact@z3bra.org> 4 * 5 * This program is free software: you can redistribute it and/or modify 6 * it under the terms of the GNU General Public License as published by 7 * the Free Software Foundation, either version 3 of the License, or 8 * (at your option) any later version. 9 * 10 * This program is distributed in the hope that it will be useful, 11 * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 * GNU General Public License for more details. 14 * 15 * You should have received a copy of the GNU General Public License 16 * along with this program. If not, see <https://www.gnu.org/licenses/>. 17 */ 18 19 #ifndef SCOPEGUARD_H 20 #define SCOPEGUARD_H 21 22 template<typename Func> 23 class ScopeGuard 24 { 25 public: 26 ScopeGuard(Func &&func) 27 : mFunc(std::move(func)) 28 {} 29 30 ScopeGuard(ScopeGuard<Func> &&) = default; 31 ScopeGuard<Func> &operator=(ScopeGuard<Func> &&) = default; 32 ScopeGuard(const ScopeGuard<Func> &) = delete; 33 ScopeGuard<Func> &operator=(const ScopeGuard<Func> &) = delete; 34 35 ~ScopeGuard() 36 { 37 mFunc(); 38 } 39 40 private: 41 Func mFunc; 42 }; 43 44 template<typename Func> 45 ScopeGuard<Func> scopeGuard(Func &&func) 46 { 47 return ScopeGuard<Func>(std::move(func)); 48 } 49 50 #endif // SCOPEGUARD_H