about summary refs log tree commit diff
path: root/absl/utility/utility.h
diff options
context:
space:
mode:
authorAbseil Team <absl-team@google.com>2018-04-25T17·38-0700
committerDerek Mauro <dmauro@google.com>2018-04-25T17·44-0400
commitea0e750e52ee223db34a242f9a7229ac04a0f473 (patch)
tree993e0c54fcab171bccc28bc5c646653f6e8c5638 /absl/utility/utility.h
parent19b3c95727316cef3b0b40eaf37f6645a876f8d2 (diff)
- 2f6a3c92ce0f64e0923ad326ec5d07eae03061fd Add C++14's std::exchange to absl/utility/utility.h. by Abseil Team <absl-team@google.com>
  - 9f2c9adbf998dd9062c8cc3da1076bde87081d71 Fix comment typo. by Greg Falcon <gfalcon@google.com>

GitOrigin-RevId: 2f6a3c92ce0f64e0923ad326ec5d07eae03061fd
Change-Id: I7b9db94ad315092baefe56b02f250acadafbe312
Diffstat (limited to 'absl/utility/utility.h')
-rw-r--r--absl/utility/utility.h22
1 files changed, 22 insertions, 0 deletions
diff --git a/absl/utility/utility.h b/absl/utility/utility.h
index 5b9b84e05d84..d73602c47d3b 100644
--- a/absl/utility/utility.h
+++ b/absl/utility/utility.h
@@ -24,6 +24,7 @@
 //   * make_index_sequence<N>        == std::make_index_sequence<N>
 //   * index_sequence_for<Ts...>     == std::index_sequence_for<Ts...>
 //   * apply<Functor, Tuple>         == std::apply<Functor, Tuple>
+//   * exchange<T>                   == std::exchange<T>
 //
 // This header file also provides the tag types `in_place_t`, `in_place_type_t`,
 // and `in_place_index_t`, as well as the constant `in_place`, and
@@ -264,6 +265,27 @@ auto apply(Functor&& functor, Tuple&& t)
       absl::make_index_sequence<std::tuple_size<
           typename std::remove_reference<Tuple>::type>::value>{});
 }
+
+// exchange
+//
+// Replaces the value of `obj` with `new_value` and returns the old value of
+// `obj`.  `absl::exchange` is designed to be a drop-in replacement for C++14's
+// `std::exchange`.
+//
+// Example:
+//
+//   Foo& operator=(Foo&& other) {
+//     ptr1_ = absl::exchange(other.ptr1_, nullptr);
+//     int1_ = absl::exchange(other.int1_, -1);
+//     return *this;
+//   }
+template <typename T, typename U = T>
+T exchange(T& obj, U&& new_value) {
+  T old_value = absl::move(obj);
+  obj = absl::forward<U>(new_value);
+  return old_value;
+}
+
 }  // namespace absl
 
 #endif  // ABSL_UTILITY_UTILITY_H_