OLD | NEW |
(Empty) | |
| 1 // Copyright 2015 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 |
| 5 #ifndef COMPONENTS_METRICS_LEAK_DETECTOR_STL_ALLOCATOR_H_ |
| 6 #define COMPONENTS_METRICS_LEAK_DETECTOR_STL_ALLOCATOR_H_ |
| 7 |
| 8 #include <stddef.h> |
| 9 |
| 10 #include <limits> |
| 11 #include <memory> |
| 12 |
| 13 #include "base/logging.h" |
| 14 |
| 15 // Generic allocator class for STL objects. |
| 16 // deallocate() to use the template class Alloc's allocation. |
| 17 // that uses a given type-less allocator Alloc, which must provide: |
| 18 // static void* Alloc::Allocate(size_t size); |
| 19 // static void Alloc::Free(void* ptr, size_t size); |
| 20 // |
| 21 // Inherits from the default allocator, std::allocator. Overrides allocate() and |
| 22 // |
| 23 // STL_Allocator<T, MyAlloc> provides the same thread-safety |
| 24 // guarantees as MyAlloc. |
| 25 // |
| 26 // Usage example: |
| 27 // set<T, less<T>, STL_Allocator<T, MyAlloc> > my_set; |
| 28 |
| 29 template <typename T, class Alloc> |
| 30 class STL_Allocator : public std::allocator<T> { |
| 31 public: |
| 32 typedef size_t size_type; |
| 33 typedef T* pointer; |
| 34 |
| 35 template <class T1> struct rebind { |
| 36 typedef STL_Allocator<T1, Alloc> other; |
| 37 }; |
| 38 |
| 39 STL_Allocator() {} |
| 40 explicit STL_Allocator(const STL_Allocator&) {} |
| 41 template <class T1> STL_Allocator(const STL_Allocator<T1, Alloc>&) {} |
| 42 ~STL_Allocator() {} |
| 43 |
| 44 pointer allocate(size_type n, const void* = 0) { |
| 45 // Make sure the computation of the total allocation size does not cause an |
| 46 // integer overflow. |
| 47 RAW_CHECK(n < max_size()); |
| 48 return static_cast<T*>(Alloc::Allocate(n * sizeof(T))); |
| 49 } |
| 50 |
| 51 void deallocate(pointer p, size_type n) { |
| 52 Alloc::Free(p, n * sizeof(T)); |
| 53 } |
| 54 |
| 55 size_type max_size() const { |
| 56 return std::numeric_limits<size_t>::max() / sizeof(T); |
| 57 } |
| 58 }; |
| 59 |
| 60 #endif // COMPONENTS_METRICS_LEAK_DETECTOR_STL_ALLOCATOR_H_ |
OLD | NEW |