memory.h 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699
  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 ABSL_MEMORY_MEMORY_H_
  23. #define 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 "absl/base/macros.h"
  31. #include "absl/meta/type_traits.h"
  32. namespace absl {
  33. 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 `absl::WrapUnique` is useful for capturing the output of a raw
  56. // pointer factory, prefer 'absl::make_unique<T>(args...)' over
  57. // '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 `absl::WrapUnique(p)` is valid only if `delete p` is a valid
  63. // expression. In particular, `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. namespace memory_internal {
  73. // Traits to select proper overload and return type for `absl::make_unique<>`.
  74. template <typename T>
  75. struct MakeUniqueResult {
  76. using scalar = std::unique_ptr<T>;
  77. };
  78. template <typename T>
  79. struct MakeUniqueResult<T[]> {
  80. using array = std::unique_ptr<T[]>;
  81. };
  82. template <typename T, size_t N>
  83. struct MakeUniqueResult<T[N]> {
  84. using invalid = void;
  85. };
  86. } // namespace memory_internal
  87. // gcc 4.8 has __cplusplus at 201301 but the libstdc++ shipped with it doesn't
  88. // define make_unique. Other supported compilers either just define __cplusplus
  89. // as 201103 but have make_unique (msvc), or have make_unique whenever
  90. // __cplusplus > 201103 (clang).
  91. #if (__cplusplus > 201103L || defined(_MSC_VER)) && \
  92. !(defined(__GLIBCXX__) && !defined(__cpp_lib_make_unique))
  93. using std::make_unique;
  94. #else
  95. // -----------------------------------------------------------------------------
  96. // Function Template: make_unique<T>()
  97. // -----------------------------------------------------------------------------
  98. //
  99. // Creates a `std::unique_ptr<>`, while avoiding issues creating temporaries
  100. // during the construction process. `absl::make_unique<>` also avoids redundant
  101. // type declarations, by avoiding the need to explicitly use the `new` operator.
  102. //
  103. // This implementation of `absl::make_unique<>` is designed for C++11 code and
  104. // will be replaced in C++14 by the equivalent `std::make_unique<>` abstraction.
  105. // `absl::make_unique<>` is designed to be 100% compatible with
  106. // `std::make_unique<>` so that the eventual migration will involve a simple
  107. // rename operation.
  108. //
  109. // For more background on why `std::unique_ptr<T>(new T(a,b))` is problematic,
  110. // see Herb Sutter's explanation on
  111. // (Exception-Safe Function Calls)[https://herbsutter.com/gotw/_102/].
  112. // (In general, reviewers should treat `new T(a,b)` with scrutiny.)
  113. //
  114. // Example usage:
  115. //
  116. // auto p = make_unique<X>(args...); // 'p' is a std::unique_ptr<X>
  117. // auto pa = make_unique<X[]>(5); // 'pa' is a std::unique_ptr<X[]>
  118. //
  119. // Three overloads of `absl::make_unique` are required:
  120. //
  121. // - For non-array T:
  122. //
  123. // Allocates a T with `new T(std::forward<Args> args...)`,
  124. // forwarding all `args` to T's constructor.
  125. // Returns a `std::unique_ptr<T>` owning that object.
  126. //
  127. // - For an array of unknown bounds T[]:
  128. //
  129. // `absl::make_unique<>` will allocate an array T of type U[] with
  130. // `new U[n]()` and return a `std::unique_ptr<U[]>` owning that array.
  131. //
  132. // Note that 'U[n]()' is different from 'U[n]', and elements will be
  133. // value-initialized. Note as well that `std::unique_ptr` will perform its
  134. // own destruction of the array elements upon leaving scope, even though
  135. // the array [] does not have a default destructor.
  136. //
  137. // NOTE: an array of unknown bounds T[] may still be (and often will be)
  138. // initialized to have a size, and will still use this overload. E.g:
  139. //
  140. // auto my_array = absl::make_unique<int[]>(10);
  141. //
  142. // - For an array of known bounds T[N]:
  143. //
  144. // `absl::make_unique<>` is deleted (like with `std::make_unique<>`) as
  145. // this overload is not useful.
  146. //
  147. // NOTE: an array of known bounds T[N] is not considered a useful
  148. // construction, and may cause undefined behavior in templates. E.g:
  149. //
  150. // auto my_array = absl::make_unique<int[10]>();
  151. //
  152. // In those cases, of course, you can still use the overload above and
  153. // simply initialize it to its desired size:
  154. //
  155. // auto my_array = absl::make_unique<int[]>(10);
  156. // `absl::make_unique` overload for non-array types.
  157. template <typename T, typename... Args>
  158. typename memory_internal::MakeUniqueResult<T>::scalar make_unique(
  159. Args&&... args) {
  160. return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
  161. }
  162. // `absl::make_unique` overload for an array T[] of unknown bounds.
  163. // The array allocation needs to use the `new T[size]` form and cannot take
  164. // element constructor arguments. The `std::unique_ptr` will manage destructing
  165. // these array elements.
  166. template <typename T>
  167. typename memory_internal::MakeUniqueResult<T>::array make_unique(size_t n) {
  168. return std::unique_ptr<T>(new typename absl::remove_extent_t<T>[n]());
  169. }
  170. // `absl::make_unique` overload for an array T[N] of known bounds.
  171. // This construction will be rejected.
  172. template <typename T, typename... Args>
  173. typename memory_internal::MakeUniqueResult<T>::invalid make_unique(
  174. Args&&... /* args */) = delete;
  175. #endif
  176. // -----------------------------------------------------------------------------
  177. // Function Template: RawPtr()
  178. // -----------------------------------------------------------------------------
  179. //
  180. // Extracts the raw pointer from a pointer-like value `ptr`. `absl::RawPtr` is
  181. // useful within templates that need to handle a complement of raw pointers,
  182. // `std::nullptr_t`, and smart pointers.
  183. template <typename T>
  184. auto RawPtr(T&& ptr) -> decltype(std::addressof(*ptr)) {
  185. // ptr is a forwarding reference to support Ts with non-const operators.
  186. return (ptr != nullptr) ? std::addressof(*ptr) : nullptr;
  187. }
  188. inline std::nullptr_t RawPtr(std::nullptr_t) { return nullptr; }
  189. // -----------------------------------------------------------------------------
  190. // Function Template: ShareUniquePtr()
  191. // -----------------------------------------------------------------------------
  192. //
  193. // Adopts a `std::unique_ptr` rvalue and returns a `std::shared_ptr` of deduced
  194. // type. Ownership (if any) of the held value is transferred to the returned
  195. // shared pointer.
  196. //
  197. // Example:
  198. //
  199. // auto up = absl::make_unique<int>(10);
  200. // auto sp = absl::ShareUniquePtr(std::move(up)); // shared_ptr<int>
  201. // CHECK_EQ(*sp, 10);
  202. // CHECK(up == nullptr);
  203. //
  204. // Note that this conversion is correct even when T is an array type, and more
  205. // generally it works for *any* deleter of the `unique_ptr` (single-object
  206. // deleter, array deleter, or any custom deleter), since the deleter is adopted
  207. // by the shared pointer as well. The deleter is copied (unless it is a
  208. // reference).
  209. //
  210. // Implements the resolution of [LWG 2415](http://wg21.link/lwg2415), by which a
  211. // null shared pointer does not attempt to call the deleter.
  212. template <typename T, typename D>
  213. std::shared_ptr<T> ShareUniquePtr(std::unique_ptr<T, D>&& ptr) {
  214. return ptr ? std::shared_ptr<T>(std::move(ptr)) : std::shared_ptr<T>();
  215. }
  216. // -----------------------------------------------------------------------------
  217. // Function Template: WeakenPtr()
  218. // -----------------------------------------------------------------------------
  219. //
  220. // Creates a weak pointer associated with a given shared pointer. The returned
  221. // value is a `std::weak_ptr` of deduced type.
  222. //
  223. // Example:
  224. //
  225. // auto sp = std::make_shared<int>(10);
  226. // auto wp = absl::WeakenPtr(sp);
  227. // CHECK_EQ(sp.get(), wp.lock().get());
  228. // sp.reset();
  229. // CHECK(wp.lock() == nullptr);
  230. //
  231. template <typename T>
  232. std::weak_ptr<T> WeakenPtr(const std::shared_ptr<T>& ptr) {
  233. return std::weak_ptr<T>(ptr);
  234. }
  235. namespace memory_internal {
  236. // ExtractOr<E, O, D>::type evaluates to E<O> if possible. Otherwise, D.
  237. template <template <typename> class Extract, typename Obj, typename Default,
  238. typename>
  239. struct ExtractOr {
  240. using type = Default;
  241. };
  242. template <template <typename> class Extract, typename Obj, typename Default>
  243. struct ExtractOr<Extract, Obj, Default, void_t<Extract<Obj>>> {
  244. using type = Extract<Obj>;
  245. };
  246. template <template <typename> class Extract, typename Obj, typename Default>
  247. using ExtractOrT = typename ExtractOr<Extract, Obj, Default, void>::type;
  248. // Extractors for the features of allocators.
  249. template <typename T>
  250. using GetPointer = typename T::pointer;
  251. template <typename T>
  252. using GetConstPointer = typename T::const_pointer;
  253. template <typename T>
  254. using GetVoidPointer = typename T::void_pointer;
  255. template <typename T>
  256. using GetConstVoidPointer = typename T::const_void_pointer;
  257. template <typename T>
  258. using GetDifferenceType = typename T::difference_type;
  259. template <typename T>
  260. using GetSizeType = typename T::size_type;
  261. template <typename T>
  262. using GetPropagateOnContainerCopyAssignment =
  263. typename T::propagate_on_container_copy_assignment;
  264. template <typename T>
  265. using GetPropagateOnContainerMoveAssignment =
  266. typename T::propagate_on_container_move_assignment;
  267. template <typename T>
  268. using GetPropagateOnContainerSwap = typename T::propagate_on_container_swap;
  269. template <typename T>
  270. using GetIsAlwaysEqual = typename T::is_always_equal;
  271. template <typename T>
  272. struct GetFirstArg;
  273. template <template <typename...> class Class, typename T, typename... Args>
  274. struct GetFirstArg<Class<T, Args...>> {
  275. using type = T;
  276. };
  277. template <typename Ptr, typename = void>
  278. struct ElementType {
  279. using type = typename GetFirstArg<Ptr>::type;
  280. };
  281. template <typename T>
  282. struct ElementType<T, void_t<typename T::element_type>> {
  283. using type = typename T::element_type;
  284. };
  285. template <typename T, typename U>
  286. struct RebindFirstArg;
  287. template <template <typename...> class Class, typename T, typename... Args,
  288. typename U>
  289. struct RebindFirstArg<Class<T, Args...>, U> {
  290. using type = Class<U, Args...>;
  291. };
  292. template <typename T, typename U, typename = void>
  293. struct RebindPtr {
  294. using type = typename RebindFirstArg<T, U>::type;
  295. };
  296. template <typename T, typename U>
  297. struct RebindPtr<T, U, void_t<typename T::template rebind<U>>> {
  298. using type = typename T::template rebind<U>;
  299. };
  300. template <typename T, typename U>
  301. constexpr bool HasRebindAlloc(...) {
  302. return false;
  303. }
  304. template <typename T, typename U>
  305. constexpr bool HasRebindAlloc(typename T::template rebind<U>::other*) {
  306. return true;
  307. }
  308. template <typename T, typename U, bool = HasRebindAlloc<T, U>(nullptr)>
  309. struct RebindAlloc {
  310. using type = typename RebindFirstArg<T, U>::type;
  311. };
  312. template <typename T, typename U>
  313. struct RebindAlloc<T, U, true> {
  314. using type = typename T::template rebind<U>::other;
  315. };
  316. } // namespace memory_internal
  317. // -----------------------------------------------------------------------------
  318. // Class Template: pointer_traits
  319. // -----------------------------------------------------------------------------
  320. //
  321. // An implementation of C++11's std::pointer_traits.
  322. //
  323. // Provided for portability on toolchains that have a working C++11 compiler,
  324. // but the standard library is lacking in C++11 support. For example, some
  325. // version of the Android NDK.
  326. //
  327. template <typename Ptr>
  328. struct pointer_traits {
  329. using pointer = Ptr;
  330. // element_type:
  331. // Ptr::element_type if present. Otherwise T if Ptr is a template
  332. // instantiation Template<T, Args...>
  333. using element_type = typename memory_internal::ElementType<Ptr>::type;
  334. // difference_type:
  335. // Ptr::difference_type if present, otherwise std::ptrdiff_t
  336. using difference_type =
  337. memory_internal::ExtractOrT<memory_internal::GetDifferenceType, Ptr,
  338. std::ptrdiff_t>;
  339. // rebind:
  340. // Ptr::rebind<U> if exists, otherwise Template<U, Args...> if Ptr is a
  341. // template instantiation Template<T, Args...>
  342. template <typename U>
  343. using rebind = typename memory_internal::RebindPtr<Ptr, U>::type;
  344. // pointer_to:
  345. // Calls Ptr::pointer_to(r)
  346. static pointer pointer_to(element_type& r) { // NOLINT(runtime/references)
  347. return Ptr::pointer_to(r);
  348. }
  349. };
  350. // Specialization for T*.
  351. template <typename T>
  352. struct pointer_traits<T*> {
  353. using pointer = T*;
  354. using element_type = T;
  355. using difference_type = std::ptrdiff_t;
  356. template <typename U>
  357. using rebind = U*;
  358. // pointer_to:
  359. // Calls std::addressof(r)
  360. static pointer pointer_to(
  361. element_type& r) noexcept { // NOLINT(runtime/references)
  362. return std::addressof(r);
  363. }
  364. };
  365. // -----------------------------------------------------------------------------
  366. // Class Template: allocator_traits
  367. // -----------------------------------------------------------------------------
  368. //
  369. // A C++11 compatible implementation of C++17's std::allocator_traits.
  370. //
  371. #if __cplusplus >= 201703L || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L)
  372. using std::allocator_traits;
  373. #else // __cplusplus >= 201703L
  374. template <typename Alloc>
  375. struct allocator_traits {
  376. using allocator_type = Alloc;
  377. // value_type:
  378. // Alloc::value_type
  379. using value_type = typename Alloc::value_type;
  380. // pointer:
  381. // Alloc::pointer if present, otherwise value_type*
  382. using pointer = memory_internal::ExtractOrT<memory_internal::GetPointer,
  383. Alloc, value_type*>;
  384. // const_pointer:
  385. // Alloc::const_pointer if present, otherwise
  386. // absl::pointer_traits<pointer>::rebind<const value_type>
  387. using const_pointer =
  388. memory_internal::ExtractOrT<memory_internal::GetConstPointer, Alloc,
  389. typename absl::pointer_traits<pointer>::
  390. template rebind<const value_type>>;
  391. // void_pointer:
  392. // Alloc::void_pointer if present, otherwise
  393. // absl::pointer_traits<pointer>::rebind<void>
  394. using void_pointer = memory_internal::ExtractOrT<
  395. memory_internal::GetVoidPointer, Alloc,
  396. typename absl::pointer_traits<pointer>::template rebind<void>>;
  397. // const_void_pointer:
  398. // Alloc::const_void_pointer if present, otherwise
  399. // absl::pointer_traits<pointer>::rebind<const void>
  400. using const_void_pointer = memory_internal::ExtractOrT<
  401. memory_internal::GetConstVoidPointer, Alloc,
  402. typename absl::pointer_traits<pointer>::template rebind<const void>>;
  403. // difference_type:
  404. // Alloc::difference_type if present, otherwise
  405. // absl::pointer_traits<pointer>::difference_type
  406. using difference_type = memory_internal::ExtractOrT<
  407. memory_internal::GetDifferenceType, Alloc,
  408. typename absl::pointer_traits<pointer>::difference_type>;
  409. // size_type:
  410. // Alloc::size_type if present, otherwise
  411. // std::make_unsigned<difference_type>::type
  412. using size_type = memory_internal::ExtractOrT<
  413. memory_internal::GetSizeType, Alloc,
  414. typename std::make_unsigned<difference_type>::type>;
  415. // propagate_on_container_copy_assignment:
  416. // Alloc::propagate_on_container_copy_assignment if present, otherwise
  417. // std::false_type
  418. using propagate_on_container_copy_assignment = memory_internal::ExtractOrT<
  419. memory_internal::GetPropagateOnContainerCopyAssignment, Alloc,
  420. std::false_type>;
  421. // propagate_on_container_move_assignment:
  422. // Alloc::propagate_on_container_move_assignment if present, otherwise
  423. // std::false_type
  424. using propagate_on_container_move_assignment = memory_internal::ExtractOrT<
  425. memory_internal::GetPropagateOnContainerMoveAssignment, Alloc,
  426. std::false_type>;
  427. // propagate_on_container_swap:
  428. // Alloc::propagate_on_container_swap if present, otherwise std::false_type
  429. using propagate_on_container_swap =
  430. memory_internal::ExtractOrT<memory_internal::GetPropagateOnContainerSwap,
  431. Alloc, std::false_type>;
  432. // is_always_equal:
  433. // Alloc::is_always_equal if present, otherwise std::is_empty<Alloc>::type
  434. using is_always_equal =
  435. memory_internal::ExtractOrT<memory_internal::GetIsAlwaysEqual, Alloc,
  436. typename std::is_empty<Alloc>::type>;
  437. // rebind_alloc:
  438. // Alloc::rebind<T>::other if present, otherwise Alloc<T, Args> if this Alloc
  439. // is Alloc<U, Args>
  440. template <typename T>
  441. using rebind_alloc = typename memory_internal::RebindAlloc<Alloc, T>::type;
  442. // rebind_traits:
  443. // absl::allocator_traits<rebind_alloc<T>>
  444. template <typename T>
  445. using rebind_traits = absl::allocator_traits<rebind_alloc<T>>;
  446. // allocate(Alloc& a, size_type n):
  447. // Calls a.allocate(n)
  448. static pointer allocate(Alloc& a, // NOLINT(runtime/references)
  449. size_type n) {
  450. return a.allocate(n);
  451. }
  452. // allocate(Alloc& a, size_type n, const_void_pointer hint):
  453. // Calls a.allocate(n, hint) if possible.
  454. // If not possible, calls a.allocate(n)
  455. static pointer allocate(Alloc& a, size_type n, // NOLINT(runtime/references)
  456. const_void_pointer hint) {
  457. return allocate_impl(0, a, n, hint);
  458. }
  459. // deallocate(Alloc& a, pointer p, size_type n):
  460. // Calls a.deallocate(p, n)
  461. static void deallocate(Alloc& a, pointer p, // NOLINT(runtime/references)
  462. size_type n) {
  463. a.deallocate(p, n);
  464. }
  465. // construct(Alloc& a, T* p, Args&&... args):
  466. // Calls a.construct(p, std::forward<Args>(args)...) if possible.
  467. // If not possible, calls
  468. // ::new (static_cast<void*>(p)) T(std::forward<Args>(args)...)
  469. template <typename T, typename... Args>
  470. static void construct(Alloc& a, T* p, // NOLINT(runtime/references)
  471. Args&&... args) {
  472. construct_impl(0, a, p, std::forward<Args>(args)...);
  473. }
  474. // destroy(Alloc& a, T* p):
  475. // Calls a.destroy(p) if possible. If not possible, calls p->~T().
  476. template <typename T>
  477. static void destroy(Alloc& a, T* p) { // NOLINT(runtime/references)
  478. destroy_impl(0, a, p);
  479. }
  480. // max_size(const Alloc& a):
  481. // Returns a.max_size() if possible. If not possible, returns
  482. // std::numeric_limits<size_type>::max() / sizeof(value_type)
  483. static size_type max_size(const Alloc& a) { return max_size_impl(0, a); }
  484. // select_on_container_copy_construction(const Alloc& a):
  485. // Returns a.select_on_container_copy_construction() if possible.
  486. // If not possible, returns a.
  487. static Alloc select_on_container_copy_construction(const Alloc& a) {
  488. return select_on_container_copy_construction_impl(0, a);
  489. }
  490. private:
  491. template <typename A>
  492. static auto allocate_impl(int, A& a, // NOLINT(runtime/references)
  493. size_type n, const_void_pointer hint)
  494. -> decltype(a.allocate(n, hint)) {
  495. return a.allocate(n, hint);
  496. }
  497. static pointer allocate_impl(char, Alloc& a, // NOLINT(runtime/references)
  498. size_type n, const_void_pointer) {
  499. return a.allocate(n);
  500. }
  501. template <typename A, typename... Args>
  502. static auto construct_impl(int, A& a, // NOLINT(runtime/references)
  503. Args&&... args)
  504. -> decltype(a.construct(std::forward<Args>(args)...)) {
  505. a.construct(std::forward<Args>(args)...);
  506. }
  507. template <typename T, typename... Args>
  508. static void construct_impl(char, Alloc&, T* p, Args&&... args) {
  509. ::new (static_cast<void*>(p)) T(std::forward<Args>(args)...);
  510. }
  511. template <typename A, typename T>
  512. static auto destroy_impl(int, A& a, // NOLINT(runtime/references)
  513. T* p) -> decltype(a.destroy(p)) {
  514. a.destroy(p);
  515. }
  516. template <typename T>
  517. static void destroy_impl(char, Alloc&, T* p) {
  518. p->~T();
  519. }
  520. template <typename A>
  521. static auto max_size_impl(int, const A& a) -> decltype(a.max_size()) {
  522. return a.max_size();
  523. }
  524. static size_type max_size_impl(char, const Alloc&) {
  525. return (std::numeric_limits<size_type>::max)() / sizeof(value_type);
  526. }
  527. template <typename A>
  528. static auto select_on_container_copy_construction_impl(int, const A& a)
  529. -> decltype(a.select_on_container_copy_construction()) {
  530. return a.select_on_container_copy_construction();
  531. }
  532. static Alloc select_on_container_copy_construction_impl(char,
  533. const Alloc& a) {
  534. return a;
  535. }
  536. };
  537. #endif // __cplusplus >= 201703L
  538. namespace memory_internal {
  539. // This template alias transforms Alloc::is_nothrow into a metafunction with
  540. // Alloc as a parameter so it can be used with ExtractOrT<>.
  541. template <typename Alloc>
  542. using GetIsNothrow = typename Alloc::is_nothrow;
  543. } // namespace memory_internal
  544. // ABSL_ALLOCATOR_NOTHROW is a build time configuration macro for user to
  545. // specify whether the default allocation function can throw or never throws.
  546. // If the allocation function never throws, user should define it to a non-zero
  547. // value (e.g. via `-DABSL_ALLOCATOR_NOTHROW`).
  548. // If the allocation function can throw, user should leave it undefined or
  549. // define it to zero.
  550. //
  551. // allocator_is_nothrow<Alloc> is a traits class that derives from
  552. // Alloc::is_nothrow if present, otherwise std::false_type. It's specialized
  553. // for Alloc = std::allocator<T> for any type T according to the state of
  554. // ABSL_ALLOCATOR_NOTHROW.
  555. //
  556. // default_allocator_is_nothrow is a class that derives from std::true_type
  557. // when the default allocator (global operator new) never throws, and
  558. // std::false_type when it can throw. It is a convenience shorthand for writing
  559. // allocator_is_nothrow<std::allocator<T>> (T can be any type).
  560. // NOTE: allocator_is_nothrow<std::allocator<T>> is guaranteed to derive from
  561. // the same type for all T, because users should specialize neither
  562. // allocator_is_nothrow nor std::allocator.
  563. template <typename Alloc>
  564. struct allocator_is_nothrow
  565. : memory_internal::ExtractOrT<memory_internal::GetIsNothrow, Alloc,
  566. std::false_type> {};
  567. #if defined(ABSL_ALLOCATOR_NOTHROW) && ABSL_ALLOCATOR_NOTHROW
  568. template <typename T>
  569. struct allocator_is_nothrow<std::allocator<T>> : std::true_type {};
  570. struct default_allocator_is_nothrow : std::true_type {};
  571. #else
  572. struct default_allocator_is_nothrow : std::false_type {};
  573. #endif
  574. namespace memory_internal {
  575. template <typename Allocator, typename Iterator, typename... Args>
  576. void ConstructRange(Allocator& alloc, Iterator first, Iterator last,
  577. const Args&... args) {
  578. for (Iterator cur = first; cur != last; ++cur) {
  579. ABSL_INTERNAL_TRY {
  580. std::allocator_traits<Allocator>::construct(alloc, std::addressof(*cur),
  581. args...);
  582. }
  583. ABSL_INTERNAL_CATCH_ANY {
  584. while (cur != first) {
  585. --cur;
  586. std::allocator_traits<Allocator>::destroy(alloc, std::addressof(*cur));
  587. }
  588. ABSL_INTERNAL_RETHROW;
  589. }
  590. }
  591. }
  592. template <typename Allocator, typename Iterator, typename InputIterator>
  593. void CopyRange(Allocator& alloc, Iterator destination, InputIterator first,
  594. InputIterator last) {
  595. for (Iterator cur = destination; first != last;
  596. static_cast<void>(++cur), static_cast<void>(++first)) {
  597. ABSL_INTERNAL_TRY {
  598. std::allocator_traits<Allocator>::construct(alloc, std::addressof(*cur),
  599. *first);
  600. }
  601. ABSL_INTERNAL_CATCH_ANY {
  602. while (cur != destination) {
  603. --cur;
  604. std::allocator_traits<Allocator>::destroy(alloc, std::addressof(*cur));
  605. }
  606. ABSL_INTERNAL_RETHROW;
  607. }
  608. }
  609. }
  610. } // namespace memory_internal
  611. ABSL_NAMESPACE_END
  612. } // namespace absl
  613. #endif // ABSL_MEMORY_MEMORY_H_