-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStackAlloc.h
More file actions
62 lines (55 loc) · 1.08 KB
/
Copy pathStackAlloc.h
File metadata and controls
62 lines (55 loc) · 1.08 KB
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
#ifndef MEMORYPOOL_STACKALLOC_H
#define MEMORYPOOL_STACKALLOC_H
#include <memory>
template <typename T>
struct StackNode_
{
/* data */
T data;
StackNode_* prev;
};
template <class T, class Alloc = std::allocator<T> >
class StackAlloc
{
public:
typedef StackNode_<T> Node;
typedef typename Alloc::template rebind<Node>::other allocator;
StackAlloc() { head_ = 0; }
~StackAlloc() { clear(); }
bool empty() { return (head_ == 0); }
void clear()
{
Node* curr = head_;
while (curr != 0)
{
Node* tmp = curr->prev;
allocator_.destory(curr);
allocator_.deallocate(curr, 1);
curr = tmp;
}
head_ = 0;
}
void push(T element)
{
Node* newNode = allocator_.allocate(1);
allocator_.construct(newNode, Node());
newNode->data = element;
newNode->prev = head_;
head_ = newNode;
}
T pop()
{
T result = head_->data;
Node* tmp = head_->prev;
allocator_.destory(head_);
allocator_.deallocate(head_, 1);
head_ = tmp;
return result;
}
T top() { return (head_->data); }
/* data */
private:
allocate allocator_;
Node* head_;
};
#endif /*MEMORYPOOL_STACKALLOC_H*/