blob: 8515fe9cd723a97edf2cb6565e5506bf421d320d [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
Sam McNally54bc0282017-12-13 02:42:298#include <utility>
9
avi9b6f42932015-12-26 22:15:1410#include "base/macros.h"
[email protected]5be7da242009-11-20 23:16:2611
[email protected]997ec9f2012-11-21 04:44:1412// base::AutoReset<> is useful for setting a variable to a new value only within
13// a particular scope. An base::AutoReset<> object resets a variable to its
14// original value upon destruction, making it an alternative to writing
15// "var = false;" or "var = old_val;" at all of a block's exit points.
[email protected]5be7da242009-11-20 23:16:2616//
[email protected]997ec9f2012-11-21 04:44:1417// This should be obvious, but note that an base::AutoReset<> instance should
18// have a shorter lifetime than its scoped_variable, to prevent invalid memory
19// writes when the base::AutoReset<> object is destroyed.
20
21namespace base {
[email protected]5be7da242009-11-20 23:16:2622
[email protected]0fbd70332010-06-01 19:28:3423template<typename T>
[email protected]5be7da242009-11-20 23:16:2624class AutoReset {
25 public:
[email protected]0fbd70332010-06-01 19:28:3426 AutoReset(T* scoped_variable, T new_value)
[email protected]5be7da242009-11-20 23:16:2627 : scoped_variable_(scoped_variable),
Sam McNally54bc0282017-12-13 02:42:2928 original_value_(std::move(*scoped_variable)) {
29 *scoped_variable_ = std::move(new_value);
[email protected]5be7da242009-11-20 23:16:2630 }
[email protected]0fbd70332010-06-01 19:28:3431
Sam McNally54bc0282017-12-13 02:42:2932 ~AutoReset() { *scoped_variable_ = std::move(original_value_); }
[email protected]5be7da242009-11-20 23:16:2633
34 private:
[email protected]0fbd70332010-06-01 19:28:3435 T* scoped_variable_;
36 T original_value_;
[email protected]5be7da242009-11-20 23:16:2637
38 DISALLOW_COPY_AND_ASSIGN(AutoReset);
39};
40
danakjc3762b92015-03-07 01:51:4241} // namespace base
[email protected]997ec9f2012-11-21 04:44:1442
[email protected]5be7da242009-11-20 23:16:2643#endif // BASE_AUTO_RESET_H_