安全C++代码pool

转自:编写安全C++代码杂谈

 1 class noncopyable
 2 {
 3  public:
 4   noncopyable(const noncopyable&) = delete;
 5   void operator=(const noncopyable&) = delete;
 6 
 7  protected:
 8   noncopyable() = default;
 9   ~noncopyable() = default;
10 };
11 
12 struct connection {
13     std::string id;
14     //...other fields
15 };
16 
17 template<typename _Tp , size_t N>
18 class object_pool final : public noncopyable {
19 public:
20     using DeleterType = std::function<void(_Tp*)>;
21     using value_u_ptr = std::unique_ptr<_Tp, DeleterType>;
22 
23     static object_pool& instance() {
24         static object_pool<_Tp, N> pool;
25         return pool;
26     }
27 
28     value_u_ptr acquire() {
29         std::lock_guard<std::mutex> lock(mtx_);
30         if (empty()) {
31             return nullptr;
32         }
33 
34         value_u_ptr ptr(pool_.front().release(), [this](_Tp* t) {
35             pool_.push_back(std::unique_ptr<_Tp>(t));
36         });
37 
38         pool_.pop_front();
39         return ptr;
40     }
41 
42     bool empty() const {
43         return pool_.empty();
44     }
45 
46     size_t size() const {
47         return pool_.size();
48     }
49 private:
50     object_pool() {
51         static_assert(N < 500, "init size is out of range");
52         for (size_t i = 0; i < N; i++) {
53             pool_.push_back(std::unique_ptr<_Tp>(new _Tp));
54         }
55     }
56 
57 private:
58     std::deque<std::unique_ptr<_Tp>> pool_;
59     std::mutex mtx_;
60 };
原文地址:https://www.cnblogs.com/water-bear/p/13474125.html