Nate Glenn
Nate Glenn

Reputation: 6744

smart pointer memory pool

I'm working on a large, old codebase that uses memory pools to great speed advantage. The problem, though, is that allocating and deallocating memory through the memory pool is complicated. I would like to try using smart pointers, but it was suggested to me that the loss in performance would be an issue.

The solution that seems to present itself is a smart pointer implementation that continues to use the original memory pool under the hood. I can't find any smart pointer/memory pool combinations in use. Can anyone point me to an example implementation of this? Are there any gotchas/cautions I should be aware of before trying this out?

Upvotes: 1

Views: 2156

Answers (2)

harmic
harmic

Reputation: 30577

Smart pointers don't generally allocate memory for the object they are pointing to - rather you create the object yourself and construct a smart pointer of the desired type from the resulting raw pointer.

However the smart pointer controls the life cycle of the object after that, so it needs to know how to free the object once it is no longer referenced, according to the rules of the smart pointer you have chosen.

The default action is to use 'delete', but you can supply your own 'custom deleter' instead.

For example:

MyClass* CreateMyObject(/* whatever args you need */) {
    // Do whatever it takes to create your object in the pool
    return myObject;
}

void DeleteMyObject(MyClass *obj) {
    // Do whatever it takes to free object from pool
}

std::shared_ptr<MyClass> ptr(CreateMyObject(....), DeleteMyObject);

I am not sure if that solves your initial concerns - you still need to handle the complexities of allocating and de-allocating your objects in the pools - but you do get the life cycle management benefits of the smart pointers.

Here is at least one tutorial on the use of custom deleters.

Upvotes: 3

Tim Ruddick
Tim Ruddick

Reputation: 1403

Andrei Alexandrescu's Modern C++ Design has a good chapter on smart pointers. The Loki library described in the book provides templates that use policy classes to tune behavior of the smart pointers to your specific needs.

Be aware, these are a different beast than C++11's std::shared_ptr, and not compatible with those. Incorporating Loki into your codebase might not be a justifiable choice, depending on your maintenance needs. But the concepts in the book are worth exploring in any case.

Upvotes: 1

Related Questions