LPCGame
A 2d game 'engine' written in C++
 All Classes Files Functions Variables Typedefs Enumerations Enumerator
objectpool.h
Go to the documentation of this file.
1 #ifndef OBJECTPOOL_H
2 #define OBJECTPOOL_H
3 
4 #include <queue>
5 #include <memory>
6 #include <stdexcept>
7 #include <thread>
8 
10 
14 template<typename T>
15 class ObjectPool{
16 public:
22  ObjectPool(size_t chunkSize = kDefaultChunkSize)
23  throw(std::invalid_argument, std::bad_alloc);
29  std::shared_ptr<T> AcquireObject();
35  void ReturnObject(std::shared_ptr<T> obj);
36 
37 protected:
39  void AllocateChunk();
40 
41 protected:
43  std::queue<std::shared_ptr<T>> mFreeList;
44  size_t mChunkSize;
45  static const size_t kDefaultChunkSize = 10;
46 
47 private:
49  ObjectPool(const ObjectPool<T> &src);
50  ObjectPool<T>& operator=(const ObjectPool<T> &rhs);
51 };
52 template<typename T> const size_t ObjectPool<T>::kDefaultChunkSize;
53 
54 template<typename T> ObjectPool<T>::ObjectPool(size_t chunkSize)
55  throw(std::invalid_argument, std::bad_alloc)
56 {
57  if (chunkSize <= 0)
58  throw std::invalid_argument("Chunk size cannot be <= 0");
59  mChunkSize = chunkSize;
60  //allocate an initial chunk of objects
61  AllocateChunk();
62 }
63 template<typename T> std::shared_ptr<T> ObjectPool<T>::AcquireObject(){
64  //if free list is empty, create more
65  if (mFreeList.empty())
66  AllocateChunk();
67  auto obj = mFreeList.front();
68  mFreeList.pop();
69  return obj;
70 }
71 template<typename T> void ObjectPool<T>::ReturnObject(std::shared_ptr<T> obj){
72  mFreeList.push(obj);
73 }
74 template<typename T> void ObjectPool<T>::AllocateChunk(){
75  for (size_t i = 0; i < mChunkSize; ++i)
76  mFreeList.push(std::make_shared<T>());
77 }
78 
79 //Trying an idea
81 
82 #endif