How do I pool allocate objects in high-performance C++?

Learn how to efficiently pool allocate objects in high-performance C++ applications to enhance performance and reduce memory fragmentation.

pool allocation, C++, memory management, high-performance programming, object pooling

#include <iostream>
#include <vector>
#include <memory>

class Object {
public:
    void doSomething() {
        std::cout << "Doing something" << std::endl;
    }
};

class ObjectPool {
private:
    std::vector<std::unique_ptr<Object>> pool;
    size_t size;
public:
    ObjectPool(size_t size) : size(size) {
        pool.reserve(size);
        for (size_t i = 0; i < size; i++) {
            pool.emplace_back(std::make_unique<Object>());
        }
    }

    Object* acquire() {
        for (auto& obj : pool) {
            if (obj) {
                Object* temp = obj.release();
                return temp;
            }
        }
        return nullptr; // No available object
    }

    void release(Object* obj) {
        pool.emplace_back(std::unique_ptr<Object>(obj));
    }
};

int main() {
    ObjectPool objectPool(10);

    // Acquire an object from the pool
    Object* obj = objectPool.acquire();
    if (obj) {
        obj->doSomething();
        // Release the object back to the pool
        objectPool.release(obj);
    }

    return 0;
}
        

pool allocation C++ memory management high-performance programming object pooling