C + + implements a Simple object pool

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.