1 /* 2 Copyright 2013-2015 Skytechnology sp. z o.o. 3 4 This file is part of LizardFS. 5 6 LizardFS is free software: you can redistribute it and/or modify 7 it under the terms of the GNU General Public License as published by 8 the Free Software Foundation, version 3. 9 10 LizardFS 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 LizardFS. If not, see <http://www.gnu.org/licenses/>. 17 */ 18 19 #pragma once 20 21 #include "common/platform.h" 22 23 #include <utility> 24 25 /** 26 * A class which calls the given function in its destructor. 27 * Usable when one wants do do some cleanup in a function which has multiple ways of exiting. 28 */ 29 template <typename Function> 30 class LambdaGuard { 31 public: LambdaGuard(Function f)32 explicit LambdaGuard(Function f) : valid_(true), f_(std::move(f)) {} 33 34 LambdaGuard(LambdaGuard&) = delete; // to make using these objects safer 35 LambdaGuard(LambdaGuard && other)36 LambdaGuard(LambdaGuard&& other) : valid_(other.valid_), f_(std::move(other.f_)) { 37 other.valid_ = false; 38 } 39 ~LambdaGuard()40 ~LambdaGuard() { 41 if (valid_) { 42 f_(); 43 } 44 } 45 46 private: 47 /// true iff we should call \p f_ in the destructor 48 bool valid_; 49 50 /// function to be called in the destructor 51 Function f_; 52 }; 53 54 /** 55 * Creates a LambdaGuard object. 56 * Usage example: see the unit test. 57 * \param f some function-like object 58 */ 59 template <typename Function> makeLambdaGuard(Function f)60LambdaGuard<Function> makeLambdaGuard(Function f) { 61 return LambdaGuard<Function>(std::move(f)); 62 } 63