Heikki Hellgren


The Object Pool Pattern

C++ Telltales part 7:

This is seventh part of my C++ Telltales series where I share some tips and tricks to work with C++. Feel free to check out also other parts of the series here!

Object pools are useful if you need to have large number of objects which have very short lifetime and especially if the cost of initialization or destruction of those objects is high. They are used to provide access to reusable objects which are either created on the fly when requested or created upon object pool initialization — which way to use this depends on how you are planning to use the object pool.

Object pools can offer great performance boost in some cases and are very often used for example in graphics particle systems, storing large bitmaps and fonts and for socket connections. Here is an example implementation of an object pool utilizing C++14. It allows initializing the pool with some number of objects, setting the maximum number of objects in the pool and also passing construction parameters for the newly created objects by utilizing C++ parameter pack. So let’s have a look at it:

It’s most likely not the perfect solution but provides ideas how to do object pools. The example uses std::unique_ptr custom deleter to return the object back to the pool once the calling context has finished working with it. It requires that the object is reseted to it’s original state using the reset functionality so that when the same object instance is used again, it will have all member variables set as they would be for a totally new instance.

Please note also that the example is not thread-safe at all so calling it from multiple threads will not work. You can easily make it thread-safe by just adding mutexes to places where the stack is being modified. You might want to make the object pool a singleton or mapleton to access it from multiple contexts easily.

Feel free to use this snippet for basis of your own object pool implementation, happy to help!

If you liked the story, please press the ❤ button below (did you know that you can give more than one clap). Also please feel free to share this story!

About me

I am Heikki Hellgren, Software Expert and technology enthusiast working at Elektrobit Automotive. My interests are in software construction, tools, automatic testing and all the new and cool stuff like AI and autonomous driving. You can follow me on Medium and Twitter and check out my websitefor more information.

More by Heikki Hellgren

Topics of interest

More Related Stories