trantor
Non-blocking I/O cross-platform TCP network library, using C++14
Toggle main menu visibility
Loading...
Searching...
No Matches
ObjectPool.h
Go to the documentation of this file.
1
14
15
#pragma once
16
17
#include <
trantor/utils/NonCopyable.h
>
18
#include <vector>
19
#include <memory>
20
#include <type_traits>
21
#include <mutex>
22
23
namespace
trantor
24
{
30
template
<
typename
T>
31
class
ObjectPool
:
public
NonCopyable,
32
public
std::enable_shared_from_this<ObjectPool<T>>
33
{
34
public
:
35
std::shared_ptr<T> getObject()
36
{
37
static_assert
(!std::is_pointer<T>::value,
38
"The parameter type of the ObjectPool template can't be "
39
"pointer type"
);
40
T *p{
nullptr
};
41
{
42
std::lock_guard<std::mutex> lock(mtx_);
43
if
(!objs_.empty())
44
{
45
p = objs_.back();
46
objs_.pop_back();
47
}
48
}
49
50
if
(p ==
nullptr
)
51
{
52
p =
new
T;
53
}
54
55
assert(p);
56
std::weak_ptr<ObjectPool<T>> weakPtr = this->shared_from_this();
57
auto
obj = std::shared_ptr<T>(p, [weakPtr](T *ptr) {
58
auto
self = weakPtr.lock();
59
if
(self)
60
{
61
std::lock_guard<std::mutex> lock(self->mtx_);
62
self->objs_.push_back(ptr);
63
}
64
else
65
{
66
delete
ptr;
67
}
68
});
69
return
obj;
70
}
71
72
private
:
73
std::vector<T *> objs_;
74
std::mutex mtx_;
75
};
76
}
// namespace trantor
NonCopyable.h
trantor::ObjectPool
This class template represents a object pool.
Definition
ObjectPool.h:33
trantor
Definition
EventLoop.h:34
trantor
utils
ObjectPool.h
Generated by
1.17.0