-
Notifications
You must be signed in to change notification settings - Fork 1
/
pool.h
53 lines (45 loc) · 1.04 KB
/
pool.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
#ifndef JWUTIL_POOL_H
#define JWUTIL_POOL_H
#include <deque>
#include <vector>
namespace jw_util
{
template <typename Type, bool shrink = false, typename ContainerType = std::deque<Type>>
class Pool
{
public:
template <typename... ArgTypes>
Type *alloc(ArgTypes &&... args)
{
if (freed.empty())
{
pool.emplace_back(std::forward<ArgTypes>(args)...);
return &pool.back();
}
else
{
Type *res = freed.back();
freed.pop_back();
return new (res) Type(std::forward<ArgTypes>(args)...);
}
}
void free(const Type *type)
{
if (shrink && type == &pool.back())
{
pool.pop_back();
}
else
{
type->Type::~Type();
freed.push_back(const_cast<Type *>(type));
}
}
const ContainerType &get_data() const {return pool;}
ContainerType &get_data() {return pool;}
private:
ContainerType pool;
std::vector<Type *> freed;
};
}
#endif // JWUTIL_POOL_H