auto_reset.h 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. #include "base/memory/raw_ptr_exclusion.h"
  8. // base::AutoReset<> is useful for setting a variable to a new value only within
  9. // a particular scope. An base::AutoReset<> object resets a variable to its
  10. // original value upon destruction, making it an alternative to writing
  11. // "var = false;" or "var = old_val;" at all of a block's exit points.
  12. //
  13. // This should be obvious, but note that an base::AutoReset<> instance should
  14. // have a shorter lifetime than its scoped_variable, to prevent invalid memory
  15. // writes when the base::AutoReset<> object is destroyed.
  16. namespace base {
  17. template <typename T>
  18. class AutoReset {
  19. public:
  20. template <typename U>
  21. AutoReset(T* scoped_variable, U&& new_value)
  22. : scoped_variable_(scoped_variable),
  23. original_value_(
  24. std::exchange(*scoped_variable_, std::forward<U>(new_value))) {}
  25. AutoReset(AutoReset&& other)
  26. : scoped_variable_(std::exchange(other.scoped_variable_, nullptr)),
  27. original_value_(std::move(other.original_value_)) {}
  28. AutoReset& operator=(AutoReset&& rhs) {
  29. scoped_variable_ = std::exchange(rhs.scoped_variable_, nullptr);
  30. original_value_ = std::move(rhs.original_value_);
  31. return *this;
  32. }
  33. ~AutoReset() {
  34. if (scoped_variable_)
  35. *scoped_variable_ = std::move(original_value_);
  36. }
  37. private:
  38. // `scoped_variable_` is not a raw_ptr<T> for performance reasons: Large
  39. // number of non-PartitionAlloc pointees + AutoReset is typically short-lived
  40. // (e.g. allocated on the stack).
  41. RAW_PTR_EXCLUSION T* scoped_variable_;
  42. T original_value_;
  43. };
  44. } // namespace base
  45. #endif // BASE_AUTO_RESET_H_