Line data Source code
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:
37 13631 : explicit AutoRestore(T& aValue MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
38 : : mLocation(aValue)
39 13631 : , mValue(aValue)
40 : {
41 13631 : MOZ_GUARD_OBJECT_NOTIFIER_INIT;
42 13631 : }
43 13631 : ~AutoRestore()
44 : {
45 13631 : mLocation = mValue;
46 13631 : }
47 27 : T SavedValue() const
48 : {
49 27 : return mValue;
50 : }
51 : };
52 :
53 : } // namespace mozilla
54 :
55 : #endif /* !defined(mozilla_AutoRestore_h_) */
|