auto_reset.h 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // Copyright (c) 2011 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. #ifndef BASE_AUTO_RESET_H_
  5. #define BASE_AUTO_RESET_H_
  6. #include <utility>
  7. // base::AutoReset<> is useful for setting a variable to a new value only within
  8. // a particular scope. An base::AutoReset<> object resets a variable to its
  9. // original value upon destruction, making it an alternative to writing
  10. // "var = false;" or "var = old_val;" at all of a block's exit points.
  11. //
  12. // This should be obvious, but note that an base::AutoReset<> instance should
  13. // have a shorter lifetime than its scoped_variable, to prevent invalid memory
  14. // writes when the base::AutoReset<> object is destroyed.
  15. namespace base {
  16. template <typename T>
  17. class AutoReset {
  18. public:
  19. template <typename U>
  20. AutoReset(T* scoped_variable, U&& new_value)
  21. : scoped_variable_(scoped_variable),
  22. original_value_(
  23. std::exchange(*scoped_variable_, std::forward<U>(new_value))) {}
  24. AutoReset(AutoReset&& other)
  25. : scoped_variable_(std::exchange(other.scoped_variable_, nullptr)),
  26. original_value_(std::move(other.original_value_)) {}
  27. AutoReset& operator=(AutoReset&& rhs) {
  28. scoped_variable_ = std::exchange(rhs.scoped_variable_, nullptr);
  29. original_value_ = std::move(rhs.original_value_);
  30. return *this;
  31. }
  32. ~AutoReset() {
  33. if (scoped_variable_)
  34. *scoped_variable_ = std::move(original_value_);
  35. }
  36. private:
  37. T* scoped_variable_;
  38. T original_value_;
  39. };
  40. } // namespace base
  41. #endif // BASE_AUTO_RESET_H_