template class mrpt::system::CGenericMemoryPool

Overview

A generic system for versatile memory pooling.

This class implements the singleton pattern so a unique instance exists for each combination of template parameters. All methods are thread-safe.

Basic usage:

  • When needed, call request_memory() to check the availability of memory in the pool.

    • At your class destructor, donate the memory to the pool with dump_to_pool().

Notice that memory requests are checked against memory blocks in the pool via a user-defined function:

bool POOLABLE_DATA::isSuitable(const POOLABLE_DATA & req) const { ... }

For an example of how to handle a memory pool, see the class mrpt::obs::CObservation3DRangeScan

Parameters:

POOLABLE_DATA

A struct with user-defined objects which actually contain the memory blocks (e.g. one or more std::vector).

DATA_PARAMS

A struct with user information about each memory block (e.g. size of a std::vector)

#include <mrpt/system/CGenericMemoryPool.h>

template <class DATA_PARAMS, class POOLABLE_DATA>
class CGenericMemoryPool
{
public:
    // methods

    size_t getMemoryPoolMaxSize() const;
    void setMemoryPoolMaxSize(size_t maxNumEntries);
    POOLABLE_DATA* request_memory(const DATA_PARAMS& params);
    void dump_to_pool(const DATA_PARAMS& params, POOLABLE_DATA* block);
    static CGenericMemoryPool<DATA_PARAMS, POOLABLE_DATA>* getInstance(size_t max_pool_entries = 5);
};

Methods

POOLABLE_DATA* request_memory(const DATA_PARAMS& params)

Request a block of data which fulfils the size requirements stated in params.

Notice that the decision on the suitability of each pool’ed block is done by DATA_PARAMS::isSuitable(). It is a responsibility of the user to free with “delete” the “POOLABLE_DATA” object itself once the memory has been extracted from its elements.

Returns:

The block of data, or nullptr if none suitable was found in the pool.

void dump_to_pool(const DATA_PARAMS& params, POOLABLE_DATA* block)

Saves the passed data block (characterized by params) to the pool.

If the overall size of the pool is above the limit, the oldest entry is removed. It is a responsibility of the user to allocate in dynamic memory the “POOLABLE_DATA” object with “new”.

static CGenericMemoryPool<DATA_PARAMS, POOLABLE_DATA>* getInstance(size_t max_pool_entries = 5)

Construct-on-first-use (~singleton) pattern: Return the unique instance of this class for a given template arguments, or nullptr if it was once created but it’s been destroyed (which means we’re in the program global destruction phase).