1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */ 3 /* This Source Code Form is subject to the terms of the Mozilla Public 4 * License, v. 2.0. If a copy of the MPL was not distributed with this 5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 6 7 /* functions for restoring saved values at the end of a C++ scope */ 8 9 #ifndef mozilla_AutoRestore_h_ 10 #define mozilla_AutoRestore_h_ 11 12 #include "mozilla/Attributes.h" // MOZ_STACK_CLASS 13 #include "mozilla/GuardObjects.h" 14 15 namespace mozilla { 16 17 /** 18 * Save the current value of a variable and restore it when the object 19 * goes out of scope. For example: 20 * { 21 * AutoRestore<bool> savePainting(mIsPainting); 22 * mIsPainting = true; 23 * 24 * // ... your code here ... 25 * 26 * // mIsPainting is reset to its old value at the end of this block 27 * } 28 */ 29 template<class T> 30 class MOZ_RAII AutoRestore 31 { 32 private: 33 T& mLocation; 34 T mValue; 35 MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER 36 public: AutoRestore(T & aValue MOZ_GUARD_OBJECT_NOTIFIER_PARAM)37 explicit AutoRestore(T& aValue MOZ_GUARD_OBJECT_NOTIFIER_PARAM) 38 : mLocation(aValue) 39 , mValue(aValue) 40 { 41 MOZ_GUARD_OBJECT_NOTIFIER_INIT; 42 } ~AutoRestore()43 ~AutoRestore() 44 { 45 mLocation = mValue; 46 } SavedValue()47 T SavedValue() const 48 { 49 return mValue; 50 } 51 }; 52 53 } // namespace mozilla 54 55 #endif /* !defined(mozilla_AutoRestore_h_) */ 56