1 /* 2 * Copyright (c) 2022 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #ifndef SCOPE_GUARD_H 17 #define SCOPE_GUARD_H 18 19 namespace Updater { 20 /* 21 * The RAII feature is used to implement scope exit protection so that resources 22 * can be released and the closure action can be performed in a unified manner when 23 * the scope exits. 24 */ 25 namespace Detail { 26 template<typename ExitAction> class ScopeGuard { 27 public: ScopeGuard(ExitAction && action)28 ScopeGuard(ExitAction &&action) : action_(action), enable_(true) {} ~ScopeGuard()29 ~ScopeGuard() 30 { 31 if (enable_) { 32 action_(); 33 } 34 } 35 Disable()36 void Disable() 37 { 38 enable_ = false; 39 } 40 41 private: 42 ExitAction action_; 43 bool enable_; 44 }; 45 46 struct ScopeExitGuardHelper {}; 47 template<typename ExitAction> 48 static inline ScopeGuard<ExitAction> operator + (ScopeExitGuardHelper, ExitAction &&action) 49 { 50 return ScopeGuard<ExitAction>(std::forward<ExitAction>(action)); 51 } 52 } 53 54 #define ON_SCOPE_EXIT(id) auto onScopeExitGuard##id = Detail::ScopeExitGuardHelper {} + [ & ] 55 56 #define CANCEL_SCOPE_EXIT_GUARD(id) onScopeExitGuard##id.Disable() 57 } 58 #endif 59