-
Notifications
You must be signed in to change notification settings - Fork 0
/
allocator.h
106 lines (88 loc) · 2.64 KB
/
allocator.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#ifndef MYTINYSTL_ALLOCATOR_H_
#define MYTINYSTL_ALLOCATOR_H_
// 这个头文件包含一个模板类 allocator,用于管理内存的分配、释放,对象的构造、析构
#include "construct.h"
#include "util.h"
namespace mystl
{
// 模版类:allocator
// 模版函数代表数据类型
template <class T>
class allocator
{
public:
typedef T value_type;
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
public:
// 定义了一些静态成员函数,用于在内存中分配、释放和构造/销毁对象
static T* allocate();
static T* allocate(size_type n);
static void deallocate(T* ptr);
static void deallocate(T* ptr,size_type n);
static void construct(T *ptr);
static void construct(T *ptr,const T& value);
static void construct(T *ptr, T&& value);
template <class... Args>
static void construct(T* ptr,Args&& ...args);
static void destroy(T* ptr);
static void destroy(T* first,T*last);
};
template <class T>
T* allocator<T>::allocate(){
return static_cast<T*>(::operator new(sizeof(T)));
}
template <class T>
T* allocator<T>::allocate(size_type n){
if( n == 0 )
return nullptr;
return static_cast<T*>(::operator new( n * sizeof(T) ));
}
template <class T>
void allocator<T>::deallocate(T* ptr)
{
if (ptr == nullptr)
return;
::operator delete(ptr);
}
template <class T>
void allocator<T>::deallocate(T* ptr, size_type /*size*/)
{
if (ptr == nullptr)
return;
::operator delete(ptr);
}
template <class T>
void allocator<T>::construct(T* ptr, const T& value)
{
mystl::construct(ptr);
}
template <class T>
void allocator<T>::construct(T* ptr, const T& value)
{
mystl::construct(ptr,value);
}
template <class T>
void allocator<T>::construct(T* ptr, T&& value)
{
mystl::construct(ptr, mystl::move(value));
}
template <class T>
template <class ...Args>
void allocator<T>::construct(T* ptr, Args&& ...args){
mystl::construct(ptr, mystl::forward<Args>(args)...);
}
template <class T>
void allocator<T>::destroy(T* ptr){
mystl::destroy(ptr);
}
template <class T>
void allocator<T>::destroy(T* first, T* last){
mystl::destroy(first,last);
}
}
#endif // !MYTINYSTL_ALLOCATOR_H_