Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- main
- #include "ObjectPool.h"
- #include <iostream>
- using namespace std;
- int counter = 0;
- struct Counted
- {
- Counted()
- {
- ++counter;
- }
- ~Counted()
- {
- --counter;
- }
- };
- void run()
- {
- //ObjectPool<char> pool;
- ObjectPool<Counted> pool;
- cout << "Counter before loop = " << counter << endl;
- try
- {
- for (int i = 0; i < 1000; ++i)
- {
- cout << "Allocating object #" << i << endl;
- pool.Allocate();
- }
- }
- catch (const bad_alloc& e)
- {
- cout << e.what() << endl;
- }
- cout << "Counter after loop = " << counter << endl;
- }
- int main()
- {
- run();
- cout << "Counter before exit = " << counter << endl;
- return 0;
- }
- ////////////////////////////////////////////////////////////////////
- ObjectPool.h
- #pragma once
- #include<algorithm>
- #include<string>
- #include<queue>
- #include<stdexcept>
- #include<set>
- using namespace std;
- template <class T>
- class ObjectPool
- {
- public:
- T* Allocate();
- T* TryAllocate();
- void Deallocate(T* object);
- ~ObjectPool();
- private:
- queue<T*> free;
- set<T*> allocated;
- };
- template <typename T>
- T* ObjectPool <T>::Allocate()
- {
- if (free.empty())
- {
- free.push(new T);
- }
- auto ret = free.front();
- free.pop();
- try
- {
- allocated.insert(ret);
- }
- catch (const bad_alloc&)
- {
- delete ret;
- throw;// проброс исключения дальше
- }
- return ret;
- }
- template <typename T>
- T* ObjectPool <T>::TryAllocate()
- {
- if (free.empty())
- {
- return nullptr;
- }
- return Allocate();
- }
- template <typename T>
- void ObjectPool <T>::Deallocate(T* object)
- {
- if (allocated.find(object) == allocated.end())
- {
- throw invalid_argument(" ");
- }
- allocated.erase(object);
- free.push(object);
- }
- template <typename T>
- ObjectPool<T>::~ObjectPool()
- {
- for (auto x : allocated)
- {
- delete x;
- }
- while (!free.empty())
- {
- auto x = free.front();
- free.pop();
- delete x;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement