trantor
Non-blocking I/O cross-platform TCP network library, using C++14
Loading...
Searching...
No Matches
ObjectPool.h
Go to the documentation of this file.
1
14
15#pragma once
16
18#include <vector>
19#include <memory>
20#include <type_traits>
21#include <mutex>
22
23namespace trantor
24{
30template <typename T>
31class 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
This class template represents a object pool.
Definition ObjectPool.h:33
Definition EventLoop.h:34