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;
- //pool.Deallocate(nullptr);
- 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<unordered_map>
- #include<memory>
- using namespace std;
- template <class T>
- class ObjectPool
- {
- public:
- T* Allocate();
- T* TryAllocate();
- void Deallocate(T* object);
- private:
- queue<unique_ptr<T>> free;
- unordered_map<T*, unique_ptr<T>> allocated;
- };
- template <typename T>
- T* ObjectPool <T>::Allocate()
- {
- if (free.empty())
- {
- free.push(make_unique<T>());
- }
- auto ptr = move(free.front());
- free.pop();
- T* ret = ptr.get();
- allocated[ret] = move(ptr);
- 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)
- {
- auto it = allocated.find(object);
- if (it == allocated.end())
- {
- throw invalid_argument(" ");
- }
- free.push(move(it->second()));
- allocated.erase(it);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement