OLD | NEW |
(Empty) | |
| 1 // |
| 2 // Copyright (C) 1999 and onwards Google, Inc. |
| 3 // |
| 4 // Author: Ray Sidney |
| 5 // |
| 6 #ifndef BASE_VARSETTER_H_ |
| 7 #define BASE_VARSETTER_H_ |
| 8 |
| 9 //#include "base/port.h" |
| 10 |
| 11 // |
| 12 // Use a VarSetter object to temporarily set an object of some sort to |
| 13 // a particular value. When the VarSetter object is destructed, the |
| 14 // underlying object will revert to its former value. |
| 15 // |
| 16 // Sample code: |
| 17 // |
| 18 #if 0 |
| 19 { |
| 20 bool b = true; |
| 21 { |
| 22 VarSetter<bool> bool_setter(&b, false); |
| 23 // Now b == false. |
| 24 } |
| 25 // Now b == true again. |
| 26 } |
| 27 #endif |
| 28 |
| 29 template <class C> |
| 30 class VarSetter { |
| 31 public: |
| 32 |
| 33 // Constructor that just sets the object to a fixed value |
| 34 VarSetter(C* object, const C& value) : object_(object), old_value_(*object) { |
| 35 *object = value; |
| 36 } |
| 37 |
| 38 ~VarSetter() { *object_ = old_value_; } |
| 39 |
| 40 private: |
| 41 |
| 42 C*const object_; |
| 43 C old_value_; |
| 44 |
| 45 // Disallow |
| 46 VarSetter(const VarSetter&); |
| 47 VarSetter& operator=(const VarSetter&); |
| 48 |
| 49 // VarSetters always live on the stack |
| 50 static void* operator new (size_t); |
| 51 static void* operator new[](size_t); // Redundant, no default ctor |
| 52 |
| 53 static void operator delete (void*); |
| 54 static void operator delete[](void*); |
| 55 }; |
| 56 |
| 57 #endif // BASE_VARSETTER_H_ |
OLD | NEW |