Object pool technology can avoidProgramCreates and deletes a large number of objects in the lifecycle. If you know that the program requires a large number of objects of the same type and the object's life cycle is very short, you can create a pool for these objects for caching.
The most difficult aspect of Object pool implementation is to record which objects are idle and which objects are being used. This implementation adopts the following method: the pointer of the idle object is saved in a queue. Each time an object is requested, the pool will send the first object in the queue to the customer, if all idle resources are used up, a new memory is allocated.
In addition, a vector is used to record all allocated objects. This vector is used only when the pool is revoked to release the memory of all objects and avoid Memory leakage.
# Include <iostream>
# Include <queue>
# Include <vector>
# Include <stdexcept>
# Include <memory>
UsingSTD: queue;
UsingSTD: vector;
Template <typename T>
ClassObjectpool
{
Public:
Objectpool (IntChunksize = kdefaultchunksize)
Throw(STD: invalid_argument, STD: bad_alloc );
~ Objectpool ();
T & acquireobject ();
VoidReleaseobject (T & OBJ );
IntGetfreenum (){ReturnMfreelist. Size ();}
Protected:
Queue <t *> mfreelist;
Vector <t *> mallobjects;
IntMchunksize;
Static Const IntKdefaultchunksize = 10;
VoidAllocatechunk ();
Static VoidArraydeleteobject (T * OBJ );
Private:
Objectpool (ConstObjectpool <t> & SRC );
Objectpool &Operator= (ConstObjectpool <t> & RHs );
};
Template <typename T>
Objectpool <t>: objectpool (IntChunksize)Throw(STD: invalid_argument, STD: bad_alloc): mchunksize (chunksize)
{
If(Mchunksize <= 0)
{
ThrowSTD: invalid_argument ("Chunk size must be positive");
}
Allocatechunk ();
}
Template <typename T>
VoidObjectpool <t>: allocatechunk ()
{
T * newobject =NewT [mchunksize];
Mallobjects. push_back (newobject );
For(IntI = 0; I <mchunksize; ++ I)
{
Mfreelist. Push (& newobject [I]);
}
}
Template <typename T>
VoidObjectpool <t>: arraydeleteobject (T * OBJ)
{
Delete [] OBJ;
}
Template <typename T>
Objectpool <t> ::~ Objectpool ()
{
For_each (mallobjects. Begin (), mallobjects. End (), arraydeleteobject );
}
Template <typename T>
T & objectpool <t >:: acquireobject ()
{
STD: cout <getfreenum () <"";
If(Mfreelist. Empty ())
{
STD: cout <"Failed! Need allocate one again"<STD: Endl;
Allocatechunk ();
}
T * pobj = mfreelist. Front ();
Mfreelist. Pop ();
STD: cout <"OK"<STD: Endl;
Return(* Pobj );
}
Template <typename T>
VoidObjectpool <t>: releaseobject (T & OBJ)
{
Mfreelist. Push (& OBJ );
}
ClassUserrequest
{
Public:
Userrequest (){}
~ Userrequest (){}
Protected:
//
};
IntMain ()
{
Objectpool <userrequest> objpool (10 );
For(IntI = 0; I <30; ++ I)
{
Userrequest ur = objpool. acquireobject ();
}
System ("Pause");
Return0;
}