blob: 9116537bfb3c073f39bcd7f9bc484228f8b2437e [file] [log] [blame]
[email protected]c9dfa2c2011-06-28 02:20:021// Copyright (c) 2011 The Chromium Authors. All rights reserved.
[email protected]5be7da242009-11-20 23:16:262// 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
avi9b6f42932015-12-26 22:15:148#include "base/macros.h"
[email protected]5be7da242009-11-20 23:16:269
[email protected]997ec9f2012-11-21 04:44:1410// base::AutoReset<> is useful for setting a variable to a new value only within
11// a particular scope. An base::AutoReset<> object resets a variable to its
12// original value upon destruction, making it an alternative to writing
13// "var = false;" or "var = old_val;" at all of a block's exit points.
[email protected]5be7da242009-11-20 23:16:2614//
[email protected]997ec9f2012-11-21 04:44:1415// This should be obvious, but note that an base::AutoReset<> instance should
16// have a shorter lifetime than its scoped_variable, to prevent invalid memory
17// writes when the base::AutoReset<> object is destroyed.
18
19namespace base {
[email protected]5be7da242009-11-20 23:16:2620
[email protected]0fbd70332010-06-01 19:28:3421template<typename T>
[email protected]5be7da242009-11-20 23:16:2622class AutoReset {
23 public:
[email protected]0fbd70332010-06-01 19:28:3424 AutoReset(T* scoped_variable, T new_value)
[email protected]5be7da242009-11-20 23:16:2625 : scoped_variable_(scoped_variable),
26 original_value_(*scoped_variable) {
27 *scoped_variable_ = new_value;
28 }
[email protected]0fbd70332010-06-01 19:28:3429
[email protected]5be7da242009-11-20 23:16:2630 ~AutoReset() { *scoped_variable_ = original_value_; }
31
32 private:
[email protected]0fbd70332010-06-01 19:28:3433 T* scoped_variable_;
34 T original_value_;
[email protected]5be7da242009-11-20 23:16:2635
36 DISALLOW_COPY_AND_ASSIGN(AutoReset);
37};
38
danakjc3762b92015-03-07 01:51:4239} // namespace base
[email protected]997ec9f2012-11-21 04:44:1440
[email protected]5be7da242009-11-20 23:16:2641#endif // BASE_AUTO_RESET_H_