1 // Copyright 2016 Google Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 // 15 //////////////////////////////////////////////////////////////////////////////// 16 17 #ifndef UTIL_VARSETTER_H_ 18 #define UTIL_VARSETTER_H_ 19 20 // 21 // Use a VarSetter object to temporarily set an object of some sort to 22 // a particular value. When the VarSetter object is destructed, the 23 // underlying object will revert to its former value. 24 // 25 // Sample code: 26 // 27 #if 0 28 { 29 bool b = true; 30 { 31 VarSetter<bool> bool_setter(&b, false); 32 // Now b == false. 33 } 34 // Now b == true again. 35 } 36 #endif 37 38 template <class C> 39 class VarSetter { 40 public: 41 42 // Constructor that just sets the object to a fixed value VarSetter(C * object,const C & value)43 VarSetter(C* object, const C& value) : object_(object), old_value_(*object) { 44 *object = value; 45 } 46 ~VarSetter()47 ~VarSetter() { *object_ = old_value_; } 48 49 private: 50 51 C*const object_; 52 C old_value_; 53 54 // Disallow 55 VarSetter(const VarSetter&); 56 VarSetter& operator=(const VarSetter&); 57 58 // VarSetters always live on the stack 59 static void* operator new (size_t); 60 static void* operator new[](size_t); // Redundant, no default ctor 61 62 static void operator delete (void*); 63 static void operator delete[](void*); 64 }; 65 66 #endif // UTIL_VARSETTER_H_ 67