C++ · complete file
12_warm_pool_factory.cpp
Customize resource creation and destruction.
examples/components/12_warm_pool_factory.cpp
1// A custom WarmPool factory controls how objects are created and destroyed.2// The default factory uses new/delete. Supply a custom factory for special construction,3// such as allocating extra resources or tagging objects; the pool calls create() and dispose().456789using namespace TwoBufQueue;1011// An increasing id distinguishes a reused object from a newly created one.12struct Connection {13 int id = 0;14 bool reset(std::uint64_t) noexcept { return true; } // The connection needs no cleanup and can be reused directly.15};1617// Custom factory: create() allocates and initializes; dispose() performs complete destruction.18// dispose must be noexcept; both create and dispose run outside the pool lock.19struct ConnectionFactory {20 int next_id = 0;21 Connection* create() {22 auto* conn = new Connection;23 conn->id = ++next_id; // Assign a new increasing id to each new object.24 return conn;25 }26 void dispose(Connection* conn) const noexcept { delete conn; }27};2829int main() try {30 //---------------1. Initialize a pool with a custom factory---------------31 // The third argument is the factory; the fourth caps free objects and reclaims excess returns.32 WarmPool<Connection, true, ConnectionFactory> pool(2, 4, ConnectionFactory{}, 2);3334 //---------------2. Borrow two: the factory creates ids 1 and 2-----------35 auto a = pool.get();36 auto b = pool.get();37 if (!a || !b) throw std::runtime_error("get failed");38 if (pool.in_use_count() != 2) throw std::runtime_error("in_use_count mismatch");3940 //---------------3. Return and borrow again: reuse instead of allocation--41 if (!a.finish() || !b.finish()) throw std::runtime_error("recycle failed");4243 auto c = pool.get();44 // An id above 2 means a new object was created (id 3); a reused object has id 1 or 2.45 if (!c || c->id > 2) throw std::runtime_error("expected a reused object, not a new one");46 if (pool.resource_count() != 2) throw std::runtime_error("resource should not grow");4748 if (!c.finish()) throw std::runtime_error("recycle failed");49 if (!pool.all_released()) throw std::runtime_error("not all released");5051 std::puts("PASS: custom factory creates, pool reuses objects");52} catch (const std::exception& error) {53 std::fprintf(stderr, "%s\n", error.what());54 return 1;55}