mark@chromium.org | 4688c26 | 2011-06-28 11:20:02 +0900 | [diff] [blame] | 1 | // Copyright (c) 2011 The Chromium Authors. All rights reserved. |
pkasting@chromium.org | aea8162 | 2009-11-21 08:16:26 +0900 | [diff] [blame] | 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 | |
mark@chromium.org | 4688c26 | 2011-06-28 11:20:02 +0900 | [diff] [blame] | 10 | // AutoReset<> is useful for setting a variable to a new value only within a |
| 11 | // particular scope. An AutoReset<> object resets a variable to its original |
| 12 | // value upon destruction, making it an alternative to writing "var = false;" |
| 13 | // or "var = old_val;" at all of a block's exit points. |
pkasting@chromium.org | aea8162 | 2009-11-21 08:16:26 +0900 | [diff] [blame] | 14 | // |
mark@chromium.org | 4688c26 | 2011-06-28 11:20:02 +0900 | [diff] [blame] | 15 | // This should be obvious, but note that an AutoReset<> instance should have a |
| 16 | // shorter lifetime than its scoped_variable, to prevent invalid memory writes |
| 17 | // when the AutoReset<> object is destroyed. |
pkasting@chromium.org | aea8162 | 2009-11-21 08:16:26 +0900 | [diff] [blame] | 18 | |
gspencer@chromium.org | eb492ac | 2010-06-02 04:28:34 +0900 | [diff] [blame] | 19 | template<typename T> |
pkasting@chromium.org | aea8162 | 2009-11-21 08:16:26 +0900 | [diff] [blame] | 20 | class AutoReset { |
| 21 | public: |
gspencer@chromium.org | eb492ac | 2010-06-02 04:28:34 +0900 | [diff] [blame] | 22 | AutoReset(T* scoped_variable, T new_value) |
pkasting@chromium.org | aea8162 | 2009-11-21 08:16:26 +0900 | [diff] [blame] | 23 | : scoped_variable_(scoped_variable), |
| 24 | original_value_(*scoped_variable) { |
| 25 | *scoped_variable_ = new_value; |
| 26 | } |
gspencer@chromium.org | eb492ac | 2010-06-02 04:28:34 +0900 | [diff] [blame] | 27 | |
pkasting@chromium.org | aea8162 | 2009-11-21 08:16:26 +0900 | [diff] [blame] | 28 | ~AutoReset() { *scoped_variable_ = original_value_; } |
| 29 | |
| 30 | private: |
gspencer@chromium.org | eb492ac | 2010-06-02 04:28:34 +0900 | [diff] [blame] | 31 | T* scoped_variable_; |
| 32 | T original_value_; |
pkasting@chromium.org | aea8162 | 2009-11-21 08:16:26 +0900 | [diff] [blame] | 33 | |
| 34 | DISALLOW_COPY_AND_ASSIGN(AutoReset); |
| 35 | }; |
| 36 | |
| 37 | #endif // BASE_AUTO_RESET_H_ |