The implementation of the object pool is actually very simple
The thought is also very simple:
Use a queue to hold all objects, get an object when needed, take an object from the queue header, and then re-dedicate the object to the tail of the queue when it is exhausted.
#ifndef obj_pool_h_#define obj_pool_h_#include <queue> #include <memory> #include <stdexcept>using Std::queue;using std::shared_ptr;template <typename t>class objpool{public:objpool (int size=defaultSize) throw (Std::invalid_argument,std::bad_alloc) {if (0==size) {throw std::invalid_argument ("size can ' t not small than zero");} Msize=size;allocatechunk ();} Shared_ptr<t> Getobj () {if (Freelist.empty ()) {Allocatechunk ();} Auto Obj=freelist.front (); Freelist.pop (); return obj;} void Releaseobj (shared_ptr<t> obj) {freelist.push (obj);} protected:queue<shared_ptr<t>> freelist;int msize;static const int defaultsize=30;void allocateChunk () { for (int i=0;i<msize;i++) {Freelist.push (std::make_shared<t> ());}} Private:objpool (const objpool<t> &SRC) =delete;objpool<t> &operator= (const ObjPool<T> &RHS) =delete;}; #endif
—————————————————————————————————————————————————————————————————
Write the wrong or bad place please a lot of guidance, you can leave a message or click on the top left email address to send me an e-mail, point out my errors and shortcomings, so that I modify, better share to everyone, thank you.
Reprint Please specify source: http://blog.csdn.net/qq844352155
Author: unparalleled
Email:[email protected]
2015-7-18
In Guangzhou Tianhe load Light Road
——————————————————————————————————————————————————————————————————
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
C + + implements a Simple object pool