AutoRestore.h 1.3 KB

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