Advertisement
RobertDeMilo

BB3.13 unique_ptr для исправления утечки

Jun 13th, 2024
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.97 KB | None | 0 0
  1. main
  2.  
  3. #include "ObjectPool.h"
  4. #include <iostream>
  5.  
  6. using namespace std;
  7.  
  8. int counter = 0;
  9. struct Counted
  10. {
  11.     Counted()
  12.     {
  13.         ++counter;
  14.     }
  15.     ~Counted()
  16.     {
  17.         --counter;
  18.     }
  19. };
  20.  
  21. void run()
  22. {
  23.     //ObjectPool<char> pool;
  24.     ObjectPool<Counted> pool;
  25.     //pool.Deallocate(nullptr);
  26.  
  27.     cout << "Counter before loop = " << counter << endl;
  28.  
  29.     try
  30.     {
  31.         for (int i = 0; i < 1000; ++i)
  32.         {
  33.             cout << "Allocating object #" << i << endl;
  34.             pool.Allocate();
  35.         }
  36.     }
  37.     catch (const bad_alloc& e)
  38.     {
  39.         cout << e.what() << endl;
  40.     }
  41.    
  42.     cout << "Counter after loop = " << counter << endl;
  43. }
  44.  
  45. int main()
  46. {
  47.     run();
  48.     cout << "Counter before exit = " << counter << endl;
  49.  
  50.     return 0;
  51. }
  52.  
  53. //////////////////////////////////////////////////////////////////////////////////////////
  54. ObjectPool.h
  55.  
  56. #pragma once
  57. #include<algorithm>
  58. #include<string>
  59. #include<queue>
  60. #include<stdexcept>
  61. #include<unordered_map>
  62. #include<memory>
  63.  
  64. using namespace std;
  65.  
  66. template <class T>
  67. class ObjectPool
  68. {
  69. public:
  70.  
  71.     T* Allocate();
  72.     T* TryAllocate();
  73.  
  74.     void Deallocate(T* object);
  75.  
  76. private:
  77.  
  78.     queue<unique_ptr<T>> free;
  79.     unordered_map<T*, unique_ptr<T>> allocated;
  80. };
  81.  
  82. template <typename T>
  83. T* ObjectPool <T>::Allocate()
  84. {
  85.     if (free.empty())
  86.     {
  87.         free.push(make_unique<T>());
  88.     }
  89.     auto ptr = move(free.front());
  90.     free.pop();
  91.  
  92.     T* ret = ptr.get();
  93.     allocated[ret] = move(ptr);
  94.  
  95.     return ret;
  96. }
  97.  
  98. template <typename T>
  99. T* ObjectPool <T>::TryAllocate()
  100. {
  101.     if (free.empty())
  102.     {
  103.         return nullptr;
  104.     }
  105.     return Allocate();
  106. }
  107.  
  108. template <typename T>
  109. void ObjectPool <T>::Deallocate(T* object)
  110. {
  111.     auto it = allocated.find(object);
  112.     if (it == allocated.end())
  113.     {
  114.         throw invalid_argument(" ");
  115.     }
  116.     free.push(move(it->second()));
  117.     allocated.erase(it);
  118. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement