I want objects managed by a shared_ptr to be allocated from a pool, say Boost’s Pool interface, how can this be achieved?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Here’s the code to do what you want (probably won’t compile as I don’t have boost on hand and I’m writing it from memory):
I implemented this twice, in two different projects. In both, the create and destroy functions were synchronized (you can add a
boost::mutexlock around the use of allocator) and they were members of a factory class (and thedestroy‘s signature was modified tovoid (YourClass*)through the usage ofboost::bind).You can also avoid writing two extra functions (the
destroyandcreate) by bindingobject_pool<YourClass>::destroydirrectly in the boost::shared_ptr constructor.I’m too lazy to write all that now :).
Edit (moved my answer comment in here for the code formatting):
To bind the destroy function:
ClassFactoryshould have a longer lifetime than theshared_ptr(if theClassFactoryinstance is deleted, the this pointer passed to theshared_ptrinstance will be invalid – and crash your app when theshared_ptrdeletes theYourClassinstance).