Home | History | Annotate | Download | only in base
      1 // Copyright (c) 2009 The Chromium Authors. All rights reserved.
      2 // Use of this source code is governed by a BSD-style license that can be
      3 // found in the LICENSE file.
      4 
      5 #ifndef BASE_AUTO_RESET_H_
      6 #define BASE_AUTO_RESET_H_
      7 
      8 #include "base/basictypes.h"
      9 
     10 // AutoReset is useful for setting a variable to some value only during a
     11 // particular scope.  If you have code that has to add "var = false;" or
     12 // "var = old_var;" at all the exit points of a block, for example, you would
     13 // benefit from using this instead.
     14 //
     15 // NOTE: Right now this is hardcoded to work on bools, since that covers all the
     16 // cases where we've used it.  It would be reasonable to turn it into a template
     17 // class in the future.
     18 
     19 class AutoReset {
     20  public:
     21   explicit AutoReset(bool* scoped_variable, bool new_value)
     22       : scoped_variable_(scoped_variable),
     23         original_value_(*scoped_variable) {
     24     *scoped_variable_ = new_value;
     25   }
     26   ~AutoReset() { *scoped_variable_ = original_value_; }
     27 
     28  private:
     29   bool* scoped_variable_;
     30   bool original_value_;
     31 
     32   DISALLOW_COPY_AND_ASSIGN(AutoReset);
     33 };
     34 
     35 #endif  // BASE_AUTO_RESET_H_
     36