memory.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. // Copyright 2017 The Abseil Authors.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // https://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. //
  15. // -----------------------------------------------------------------------------
  16. // File: memory.h
  17. // -----------------------------------------------------------------------------
  18. //
  19. // This header file contains utility functions for managing the creation and
  20. // conversion of smart pointers. This file is an extension to the C++
  21. // standard <memory> library header file.
  22. #ifndef Y_ABSL_MEMORY_MEMORY_H_
  23. #define Y_ABSL_MEMORY_MEMORY_H_
  24. #include <cstddef>
  25. #include <limits>
  26. #include <memory>
  27. #include <new>
  28. #include <type_traits>
  29. #include <utility>
  30. #include "y_absl/base/macros.h"
  31. #include "y_absl/meta/type_traits.h"
  32. namespace y_absl {
  33. Y_ABSL_NAMESPACE_BEGIN
  34. // -----------------------------------------------------------------------------
  35. // Function Template: WrapUnique()
  36. // -----------------------------------------------------------------------------
  37. //
  38. // Adopts ownership from a raw pointer and transfers it to the returned
  39. // `std::unique_ptr`, whose type is deduced. Because of this deduction, *do not*
  40. // specify the template type `T` when calling `WrapUnique`.
  41. //
  42. // Example:
  43. // X* NewX(int, int);
  44. // auto x = WrapUnique(NewX(1, 2)); // 'x' is std::unique_ptr<X>.
  45. //
  46. // Do not call WrapUnique with an explicit type, as in
  47. // `WrapUnique<X>(NewX(1, 2))`. The purpose of WrapUnique is to automatically
  48. // deduce the pointer type. If you wish to make the type explicit, just use
  49. // `std::unique_ptr` directly.
  50. //
  51. // auto x = std::unique_ptr<X>(NewX(1, 2));
  52. // - or -
  53. // std::unique_ptr<X> x(NewX(1, 2));
  54. //
  55. // While `y_absl::WrapUnique` is useful for capturing the output of a raw
  56. // pointer factory, prefer 'y_absl::make_unique<T>(args...)' over
  57. // 'y_absl::WrapUnique(new T(args...))'.
  58. //
  59. // auto x = WrapUnique(new X(1, 2)); // works, but nonideal.
  60. // auto x = make_unique<X>(1, 2); // safer, standard, avoids raw 'new'.
  61. //
  62. // Note that `y_absl::WrapUnique(p)` is valid only if `delete p` is a valid
  63. // expression. In particular, `y_absl::WrapUnique()` cannot wrap pointers to
  64. // arrays, functions or void, and it must not be used to capture pointers
  65. // obtained from array-new expressions (even though that would compile!).
  66. template <typename T>
  67. std::unique_ptr<T> WrapUnique(T* ptr) {
  68. static_assert(!std::is_array<T>::value, "array types are unsupported");
  69. static_assert(std::is_object<T>::value, "non-object types are unsupported");
  70. return std::unique_ptr<T>(ptr);
  71. }
  72. // -----------------------------------------------------------------------------
  73. // Function Template: make_unique<T>()
  74. // -----------------------------------------------------------------------------
  75. //
  76. // Creates a `std::unique_ptr<>`, while avoiding issues creating temporaries
  77. // during the construction process. `y_absl::make_unique<>` also avoids redundant
  78. // type declarations, by avoiding the need to explicitly use the `new` operator.
  79. //
  80. // https://en.cppreference.com/w/cpp/memory/unique_ptr/make_unique
  81. //
  82. // For more background on why `std::unique_ptr<T>(new T(a,b))` is problematic,
  83. // see Herb Sutter's explanation on
  84. // (Exception-Safe Function Calls)[https://herbsutter.com/gotw/_102/].
  85. // (In general, reviewers should treat `new T(a,b)` with scrutiny.)
  86. //
  87. // Historical note: Abseil once provided a C++11 compatible implementation of
  88. // the C++14's `std::make_unique`. Now that C++11 support has been sunsetted,
  89. // `y_absl::make_unique` simply uses the STL-provided implementation. New code
  90. // should use `std::make_unique`.
  91. using std::make_unique;
  92. // -----------------------------------------------------------------------------
  93. // Function Template: RawPtr()
  94. // -----------------------------------------------------------------------------
  95. //
  96. // Extracts the raw pointer from a pointer-like value `ptr`. `y_absl::RawPtr` is
  97. // useful within templates that need to handle a complement of raw pointers,
  98. // `std::nullptr_t`, and smart pointers.
  99. template <typename T>
  100. auto RawPtr(T&& ptr) -> decltype(std::addressof(*ptr)) {
  101. // ptr is a forwarding reference to support Ts with non-const operators.
  102. return (ptr != nullptr) ? std::addressof(*ptr) : nullptr;
  103. }
  104. inline std::nullptr_t RawPtr(std::nullptr_t) { return nullptr; }
  105. // -----------------------------------------------------------------------------
  106. // Function Template: ShareUniquePtr()
  107. // -----------------------------------------------------------------------------
  108. //
  109. // Adopts a `std::unique_ptr` rvalue and returns a `std::shared_ptr` of deduced
  110. // type. Ownership (if any) of the held value is transferred to the returned
  111. // shared pointer.
  112. //
  113. // Example:
  114. //
  115. // auto up = y_absl::make_unique<int>(10);
  116. // auto sp = y_absl::ShareUniquePtr(std::move(up)); // shared_ptr<int>
  117. // CHECK_EQ(*sp, 10);
  118. // CHECK(up == nullptr);
  119. //
  120. // Note that this conversion is correct even when T is an array type, and more
  121. // generally it works for *any* deleter of the `unique_ptr` (single-object
  122. // deleter, array deleter, or any custom deleter), since the deleter is adopted
  123. // by the shared pointer as well. The deleter is copied (unless it is a
  124. // reference).
  125. //
  126. // Implements the resolution of [LWG 2415](http://wg21.link/lwg2415), by which a
  127. // null shared pointer does not attempt to call the deleter.
  128. template <typename T, typename D>
  129. std::shared_ptr<T> ShareUniquePtr(std::unique_ptr<T, D>&& ptr) {
  130. return ptr ? std::shared_ptr<T>(std::move(ptr)) : std::shared_ptr<T>();
  131. }
  132. // -----------------------------------------------------------------------------
  133. // Function Template: WeakenPtr()
  134. // -----------------------------------------------------------------------------
  135. //
  136. // Creates a weak pointer associated with a given shared pointer. The returned
  137. // value is a `std::weak_ptr` of deduced type.
  138. //
  139. // Example:
  140. //
  141. // auto sp = std::make_shared<int>(10);
  142. // auto wp = y_absl::WeakenPtr(sp);
  143. // CHECK_EQ(sp.get(), wp.lock().get());
  144. // sp.reset();
  145. // CHECK(wp.lock() == nullptr);
  146. //
  147. template <typename T>
  148. std::weak_ptr<T> WeakenPtr(const std::shared_ptr<T>& ptr) {
  149. return std::weak_ptr<T>(ptr);
  150. }
  151. // -----------------------------------------------------------------------------
  152. // Class Template: pointer_traits
  153. // -----------------------------------------------------------------------------
  154. //
  155. // Historical note: Abseil once provided an implementation of
  156. // `std::pointer_traits` for platforms that had not yet provided it. Those
  157. // platforms are no longer supported. New code should simply use
  158. // `std::pointer_traits`.
  159. using std::pointer_traits;
  160. // -----------------------------------------------------------------------------
  161. // Class Template: allocator_traits
  162. // -----------------------------------------------------------------------------
  163. //
  164. // Historical note: Abseil once provided an implementation of
  165. // `std::allocator_traits` for platforms that had not yet provided it. Those
  166. // platforms are no longer supported. New code should simply use
  167. // `std::allocator_traits`.
  168. using std::allocator_traits;
  169. namespace memory_internal {
  170. // ExtractOr<E, O, D>::type evaluates to E<O> if possible. Otherwise, D.
  171. template <template <typename> class Extract, typename Obj, typename Default,
  172. typename>
  173. struct ExtractOr {
  174. using type = Default;
  175. };
  176. template <template <typename> class Extract, typename Obj, typename Default>
  177. struct ExtractOr<Extract, Obj, Default, void_t<Extract<Obj>>> {
  178. using type = Extract<Obj>;
  179. };
  180. template <template <typename> class Extract, typename Obj, typename Default>
  181. using ExtractOrT = typename ExtractOr<Extract, Obj, Default, void>::type;
  182. // This template alias transforms Alloc::is_nothrow into a metafunction with
  183. // Alloc as a parameter so it can be used with ExtractOrT<>.
  184. template <typename Alloc>
  185. using GetIsNothrow = typename Alloc::is_nothrow;
  186. } // namespace memory_internal
  187. // Y_ABSL_ALLOCATOR_NOTHROW is a build time configuration macro for user to
  188. // specify whether the default allocation function can throw or never throws.
  189. // If the allocation function never throws, user should define it to a non-zero
  190. // value (e.g. via `-DABSL_ALLOCATOR_NOTHROW`).
  191. // If the allocation function can throw, user should leave it undefined or
  192. // define it to zero.
  193. //
  194. // allocator_is_nothrow<Alloc> is a traits class that derives from
  195. // Alloc::is_nothrow if present, otherwise std::false_type. It's specialized
  196. // for Alloc = std::allocator<T> for any type T according to the state of
  197. // Y_ABSL_ALLOCATOR_NOTHROW.
  198. //
  199. // default_allocator_is_nothrow is a class that derives from std::true_type
  200. // when the default allocator (global operator new) never throws, and
  201. // std::false_type when it can throw. It is a convenience shorthand for writing
  202. // allocator_is_nothrow<std::allocator<T>> (T can be any type).
  203. // NOTE: allocator_is_nothrow<std::allocator<T>> is guaranteed to derive from
  204. // the same type for all T, because users should specialize neither
  205. // allocator_is_nothrow nor std::allocator.
  206. template <typename Alloc>
  207. struct allocator_is_nothrow
  208. : memory_internal::ExtractOrT<memory_internal::GetIsNothrow, Alloc,
  209. std::false_type> {};
  210. #if defined(Y_ABSL_ALLOCATOR_NOTHROW) && Y_ABSL_ALLOCATOR_NOTHROW
  211. template <typename T>
  212. struct allocator_is_nothrow<std::allocator<T>> : std::true_type {};
  213. struct default_allocator_is_nothrow : std::true_type {};
  214. #else
  215. struct default_allocator_is_nothrow : std::false_type {};
  216. #endif
  217. namespace memory_internal {
  218. template <typename Allocator, typename Iterator, typename... Args>
  219. void ConstructRange(Allocator& alloc, Iterator first, Iterator last,
  220. const Args&... args) {
  221. for (Iterator cur = first; cur != last; ++cur) {
  222. Y_ABSL_INTERNAL_TRY {
  223. std::allocator_traits<Allocator>::construct(alloc, std::addressof(*cur),
  224. args...);
  225. }
  226. Y_ABSL_INTERNAL_CATCH_ANY {
  227. while (cur != first) {
  228. --cur;
  229. std::allocator_traits<Allocator>::destroy(alloc, std::addressof(*cur));
  230. }
  231. Y_ABSL_INTERNAL_RETHROW;
  232. }
  233. }
  234. }
  235. template <typename Allocator, typename Iterator, typename InputIterator>
  236. void CopyRange(Allocator& alloc, Iterator destination, InputIterator first,
  237. InputIterator last) {
  238. for (Iterator cur = destination; first != last;
  239. static_cast<void>(++cur), static_cast<void>(++first)) {
  240. Y_ABSL_INTERNAL_TRY {
  241. std::allocator_traits<Allocator>::construct(alloc, std::addressof(*cur),
  242. *first);
  243. }
  244. Y_ABSL_INTERNAL_CATCH_ANY {
  245. while (cur != destination) {
  246. --cur;
  247. std::allocator_traits<Allocator>::destroy(alloc, std::addressof(*cur));
  248. }
  249. Y_ABSL_INTERNAL_RETHROW;
  250. }
  251. }
  252. }
  253. } // namespace memory_internal
  254. Y_ABSL_NAMESPACE_END
  255. } // namespace y_absl
  256. #endif // Y_ABSL_MEMORY_MEMORY_H_