aboutsummaryrefslogtreecommitdiffhomepage
path: root/common.h
diff options
context:
space:
mode:
authorGravatar Cheer Xiao <xiaqqaix@gmail.com>2013-02-22 22:34:30 +0800
committerGravatar Peter Ammon <corydoras@ridiculousfish.com>2013-02-26 12:17:28 -0800
commit76f715c48613686d02a9513375065cbd7dad7921 (patch)
tree72a9df3cbdd2ec14e6d2e363db585bb8e634ab18 /common.h
parentbbab6b2fdcfeafef192f99080d2e44bb3398e942 (diff)
add class scoped_push to automatically restore variable on function exit
Diffstat (limited to 'common.h')
-rw-r--r--common.h43
1 files changed, 43 insertions, 0 deletions
diff --git a/common.h b/common.h
index f018dedf..8a10a7ef 100644
--- a/common.h
+++ b/common.h
@@ -444,6 +444,49 @@ public:
~scoped_lock();
};
+
+/**
+ A scoped manager to save the current value of some variable, and optionally
+ set it to a new value. On destruction it restores the variable to its old
+ value.
+
+ This can be handy when there are multiple code paths to exit a block.
+*/
+template <typename T>
+class scoped_push
+{
+ T &ref;
+ T saved_value;
+ bool restored;
+
+public:
+ scoped_push(T &r):
+ ref(r), restored(false)
+ {
+ saved_value = ref;
+ }
+
+ scoped_push(T &r, T new_value):
+ ref(r), restored(false)
+ {
+ saved_value = ref;
+ ref = new_value;
+ }
+
+ ~scoped_push()
+ {
+ if (!restored)
+ restore();
+ }
+
+ void restore()
+ {
+ ref = saved_value;
+ restored = true;
+ }
+};
+
+
/* Wrapper around wcstok */
class wcstokenizer
{