12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 |
- #ifndef BASE_AUTO_RESET_H_
- #define BASE_AUTO_RESET_H_
- #include <utility>
- namespace base {
- template <typename T>
- class AutoReset {
- public:
- template <typename U>
- AutoReset(T* scoped_variable, U&& new_value)
- : scoped_variable_(scoped_variable),
- original_value_(
- std::exchange(*scoped_variable_, std::forward<U>(new_value))) {}
- AutoReset(AutoReset&& other)
- : scoped_variable_(std::exchange(other.scoped_variable_, nullptr)),
- original_value_(std::move(other.original_value_)) {}
- AutoReset& operator=(AutoReset&& rhs) {
- scoped_variable_ = std::exchange(rhs.scoped_variable_, nullptr);
- original_value_ = std::move(rhs.original_value_);
- return *this;
- }
- ~AutoReset() {
- if (scoped_variable_)
- *scoped_variable_ = std::move(original_value_);
- }
- private:
- T* scoped_variable_;
- T original_value_;
- };
- }
- #endif
|