estd::object_pool
Overview
An ::estd::object_pool
is a memory manager for objects of the same type.
It allows user code to acquire
or allocate
objects from the pool and to
release
them when they are no longer needed. The pool can be configured to
provide a fixed number of elements. The ::estd::object_pool
cannot be
instantiated but is designed to be the user interface for client code.
The object_pool class is designed to store a pool of objects. Declare object_pool class is used to restrict the number of object_pools which can be created.It is a custom allocator for objects of a given type and keeps track of the items which have been acquired and released. This requires a few extra bytes of storage. The object_pool needs 1 bit for each element which requires 1 byte for every 8 elements.
Usage
The usage guidelines apply for object_pool:
Usage guidance
Size of the object pool should have a positive integer value.
Example
Declaration and usage of object pool with allocate()
// declare the object pool of size 5
::estd::declare::object_pool<int, 5> pool{};
// construct using allocate and insert value 17 and 23
auto& i1 = pool.allocate().construct(17);
pool.allocate().construct(23);
// Checking the values using position
EXPECT_EQ(17, *pool.begin());
EXPECT_EQ(17, *pool.cbegin());
// release the first one
pool.release(i1);
EXPECT_EQ(23, *pool.begin());
EXPECT_EQ(23, *pool.cbegin());
Declaration and usage of object pool with acquire()
// declare object pool p with size 10
MAKE_POOL(MyClass, 10, p);
ASSERT_EQ(10U, p.size());
// create a reference and use acquire
MyClass& a = p.acquire();
// object acquired, so size of p is reduced
ASSERT_EQ(9U, p.size());
p.acquire();
ASSERT_TRUE(p.contains(a));
ASSERT_EQ(8U, p.size());
// release the reference a
p.release(a);
// clears the objects in object pool
p.clear();