Coder
Coder

Reputation: 11

Poco::ObjectPool with c++ example

How do I use the Poco::ObjectPool class in my c++ program ? Can anyone please delineate this with an example since I am using Poco libraries for the first time. Thanking in anticipation.

Upvotes: 1

Views: 889

Answers (1)

DevSolar
DevSolar

Reputation: 70273

The documentation is pretty clear on this. Actually, all I wrote below I deducted from the docs, I've never used Poco myself... but here goes.


Let's assume you have a class Foo. For some reason you don't want to create a new one every time you need it. Perhaps it is expensive to create. Perhaps it marshals some important resource. You want to pool it, take an object from the pool, and put it back into the pool when you're done with it.

You create an Poco::ObjectPool for Foo objects, giving its starting capacity (number of objects initially created) and peak capacity.

Poco::ObjectPool< Foo > pool( 10, 20 );

You can now "borrow" objects from the pool. Note that the function can return nullptr if the peak capacity is reached.

Foo * f = pool.borrowObject();

...and return it to the pool when done.

pool.returnObject( f );

You can provide a policy class to ObjectPool to customize its behaviour, the interface being defined by PoolableObjectFactory. This class handles how objects are created, activated, validated (to check if they can be reused or need to be destroyed), deactivated, and destroyed (if they cannot be reused, or the pool gets destroyed).

struct FooFactory
{
    Foo * createObject() { return new Foo( 42 ); }
    void activateObject( Foo * p ) { p.init(); }
    bool validateObject( Foo * p ) { return true; }
    void deactivateObject( Foo * p ) { p.deinit(); }
    void destroyObject( Foo * p ) { delete p; }
};

Poco::ObjectPool< Foo, Foo *, FooFactory > pool;

Upvotes: 3

Related Questions