-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAllocator.h
executable file
·79 lines (73 loc) · 1.68 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
#ifndef _ALLOCATOR_H_
#define _ALLOCATOR_H_
#include "Alloc.h"
#include "Construct.h"
#include <cassert>
#include <new>
#include <stddef.h>
namespace My_STL{
/*
allocator直接使用Alloc.h中的alloc
*/
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:
allocator(){}
static T *allocate();
static T *allocate(size_t n);
static void deallocate(T *ptr);
static void deallocate(T *ptr, size_t n);
static void construct(T *ptr);
static void construct(T *ptr, const T& value);
static void destroy(T *ptr);
static void destroy(T *first, T *last);
};
template<class T>
T* allocator<T>::allocate(){
return static_cast<T *>(alloc::allocate(sizeof(T)));
}
/*
以元素为单位分配内存
*/
template<class T>
T* allocator<T>::allocate(size_t n){
if (n == 0) return 0;
return static_cast<T *>(alloc::allocate(sizeof(T) * n));
}
template<class T>
void allocator<T>::deallocate(T *ptr){
alloc::deallocate(static_cast<void *>(ptr), sizeof(T));
}
template<class T>
void allocator<T>::deallocate(T *ptr, size_t n){
if (n == 0) return;
alloc::deallocate(static_cast<void *>(ptr), sizeof(T)* n);
}
template<class T>
void allocator<T>::construct(T *ptr){
new(ptr)T();
}
template<class T>
void allocator<T>::construct(T *ptr, const T& value){
new(ptr)T(value);
}
template<class T>
void allocator<T>::destroy(T *ptr){
ptr->~T();
}
template<class T>
void allocator<T>::destroy(T *first, T *last){
for (; first != last; ++first){
first->~T();
}
}
}
#endif