forked from qicosmos/cosmos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SimpleObjectPool.hpp
104 lines (86 loc) · 1.96 KB
/
SimpleObjectPool.hpp
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
#pragma once
#include <memory>
#include <vector>
#include <functional>
template <class T>
class SimpleObjectPool
{
public:
using DeleterType = std::function<void(T*)>;
void add(std::unique_ptr<T> t)
{
pool_.push_back(std::move(t));
}
std::unique_ptr<T, DeleterType> get()
{
if (pool_.empty())
{
throw std::logic_error("no more object");
}
//every time add custom deleter for default unique_ptr
std::unique_ptr<T, DeleterType> ptr(pool_.back().release(), [this](T* t)
{
pool_.push_back(std::unique_ptr<T>(t));
});
pool_.pop_back();
return std::move(ptr);
}
std::shared_ptr<T> get_shared()
{
if (pool_.empty())
{
throw std::logic_error("no more object");
}
auto pin = std::unique_ptr<T>(std::move(pool_.back()));
pool_.pop_back();
return std::shared_ptr<T>(pin.release(), [this](T* t)
{
pool_.push_back(std::unique_ptr<T>(t));
});
}
bool empty() const
{
return pool_.empty();
}
size_t size() const
{
return pool_.size();
}
private:
std::vector<std::unique_ptr<T>> pool_;
};
//test code
void test_object_pool()
{
SimpleObjectPool<A> p;
p.add(std::unique_ptr<A>(new A()));
p.add(std::unique_ptr<A>(new A()));
{
auto t = p.get();
p.get();
}
{
p.get();
p.get();
}
std::cout << p.size() << std::endl;
}
//for shared_ptr
std::shared_ptr<T> get()
{
if (pool_.empty())
{
throw std::logic_error("no more object");
}
std::shared_ptr<T> ptr = pool_.back();
auto p = std::shared_ptr<T>(new T(std::move(*ptr.get())), [this](T* t)
{
pool_.push_back(std::shared_ptr<T>(t));
});
//std::unique_ptr<T, DeleterType> ptr(pool_.back().release(), [this](T* t)
//{
// pool_.push_back(std::unique_ptr<T>(t));
//});
pool_.pop_back();
return p;
}