VisuTwin Canvas
C++ 3D Engine — Metal Backend
Loading...
Searching...
No Matches
objectPool.h
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2025-2026 Arnis Lektauers
3#pragma once
4
5#include <functional>
6#include <memory>
7#include <vector>
8
9namespace visutwin::canvas
10{
11 template<typename T>
13 {
14 public:
15 using Constructor = std::function<std::unique_ptr<T>()>;
16
17 explicit ObjectPool(const size_t size = 1)
18 : ObjectPool([] { return std::make_unique<T>(); }, size)
19 {
20 }
21
22 ObjectPool(Constructor constructorFunc, const size_t size = 1)
23 : _constructor(std::move(constructorFunc))
24 {
25 resize(size);
26 }
27
29 {
30 if (_count >= _pool.size()) {
31 resize(_pool.empty() ? 1 : _pool.size() * 2);
32 }
33 return _pool[_count++].get();
34 }
35
36 void freeAll()
37 {
38 _count = 0;
39 }
40
41 [[nodiscard]] size_t count() const
42 {
43 return _count;
44 }
45
46 [[nodiscard]] size_t size() const
47 {
48 return _pool.size();
49 }
50
51 private:
52 void resize(const size_t size)
53 {
54 if (size <= _pool.size()) {
55 return;
56 }
57
58 for (size_t i = _pool.size(); i < size; ++i) {
59 _pool.push_back(_constructor ? _constructor() : std::make_unique<T>());
60 }
61 }
62
63 Constructor _constructor;
64 std::vector<std::unique_ptr<T>> _pool;
65 size_t _count = 0;
66 };
67}
std::function< std::unique_ptr< T >()> Constructor
Definition objectPool.h:15
ObjectPool(Constructor constructorFunc, const size_t size=1)
Definition objectPool.h:22
ObjectPool(const size_t size=1)
Definition objectPool.h:17