Line | |
---|
1 | /* -*- C++ -*- */ |
---|
2 | |
---|
3 | #ifndef _BOUNDEDFREELISTHEAP_H_ |
---|
4 | #define _BOUNDEDFREELISTHEAP_H_ |
---|
5 | |
---|
6 | // Beware -- this is for one "size class" only!! |
---|
7 | |
---|
8 | template <int numObjects, class Super> |
---|
9 | class BoundedFreeListHeap : public Super { |
---|
10 | public: |
---|
11 | |
---|
12 | BoundedFreeListHeap (void) |
---|
13 | : nObjects (0), |
---|
14 | myFreeList (NULL) |
---|
15 | {} |
---|
16 | |
---|
17 | ~BoundedFreeListHeap (void) |
---|
18 | { |
---|
19 | clear(); |
---|
20 | } |
---|
21 | |
---|
22 | inline void * malloc (size_t sz) { |
---|
23 | // Check the free list first. |
---|
24 | void * ptr = myFreeList; |
---|
25 | if (ptr == NULL) { |
---|
26 | ptr = Super::malloc (sz); |
---|
27 | } else { |
---|
28 | myFreeList = myFreeList->next; |
---|
29 | } |
---|
30 | return ptr; |
---|
31 | } |
---|
32 | |
---|
33 | inline void free (void * ptr) { |
---|
34 | if (nObjects < numObjects) { |
---|
35 | // Add this object to the free list. |
---|
36 | ((freeObject *) ptr)->next = myFreeList; |
---|
37 | myFreeList = (freeObject *) ptr; |
---|
38 | nObjects++; |
---|
39 | } else { |
---|
40 | clear(); |
---|
41 | // Super::free (ptr); |
---|
42 | } |
---|
43 | } |
---|
44 | |
---|
45 | inline void clear (void) { |
---|
46 | // Delete everything on the free list. |
---|
47 | void * ptr = myFreeList; |
---|
48 | while (ptr != NULL) { |
---|
49 | void * oldptr = ptr; |
---|
50 | ptr = (void *) ((freeObject *) ptr)->next; |
---|
51 | Super::free (oldptr); |
---|
52 | } |
---|
53 | myFreeList = NULL; |
---|
54 | nObjects = 0; |
---|
55 | } |
---|
56 | |
---|
57 | private: |
---|
58 | |
---|
59 | class freeObject { |
---|
60 | public: |
---|
61 | freeObject * next; |
---|
62 | }; |
---|
63 | |
---|
64 | int nObjects; |
---|
65 | freeObject * myFreeList; |
---|
66 | }; |
---|
67 | |
---|
68 | #endif |
---|
Note: See
TracBrowser
for help on using the repository browser.