AUI Framework  develop
Cross-platform base for C++ UI apps
Loading...
Searching...
No Matches
APool.h
1/*
2 * AUI Framework - Declarative UI toolkit for modern C++20
3 * Copyright (C) 2020-2024 Alex2772 and Contributors
4 *
5 * SPDX-License-Identifier: MPL-2.0
6 *
7 * This Source Code Form is subject to the terms of the Mozilla Public
8 * License, v. 2.0. If a copy of the MPL was not distributed with this
9 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
10 */
11
12#pragma once
13
14#include <functional>
15#include <AUI/Common/AQueue.h>
16#include <AUI/Common/SharedPtrTypes.h>
17
18template<typename T>
19class APool: public aui::noncopyable {
20private:
21 using Factory = std::function<_unique<T>()>;
22 Factory mFactory;
23 AQueue<_unique<T>> mQueue;
24 std::shared_ptr<bool> mPoolAlive = std::make_shared<bool>(true);
25
26
27 template <typename Ptr = _<T>>
28 Ptr getImpl() noexcept {
29 _unique<T> t;
30 if (mQueue.empty()) {
31 t = mFactory();
32 } else {
33 t = std::move(mQueue.front());
34 mQueue.pop();
35 }
36 if constexpr (std::is_same_v<Ptr, _<T>>) {
37 return aui::ptr::manage(t.release(), APoolDeleter(this));
38 } else {
39 return std::unique_ptr<T, APoolDeleter>(t.release(), APoolDeleter(this));
40 }
41 }
42
43public:
44 explicit APool(Factory factory) noexcept : mFactory(std::move(factory)) {}
45
46 struct APoolDeleter {
47 APool<T>* pool;
48 std::shared_ptr<bool> poolAlive;
49
50 APoolDeleter(APool<T>* pool) : pool(pool), poolAlive(pool->mPoolAlive) {}
51
52 void operator()(T* t) {
53 if (*poolAlive) {
54 pool->mQueue.push(_unique<T>(t));
55 } else {
56 delete t;
57 }
58 }
59 };
60
61 ~APool() {
62 *mPoolAlive = false;
63 }
64 auto get() noexcept {
65 return getImpl<_<T>>();
66 }
67
68 using UniquePtr = std::unique_ptr<T, APoolDeleter>;
69
70 auto getUnique() noexcept {
71 return getImpl<UniquePtr>();
72 }
73};
74
A std::queue with AUI extensions.
Definition AQueue.h:24
Definition APool.h:46
Forbids copy of your class.
Definition values.h:40
static _< T > manage(T *raw)
Delegates memory management of the raw pointer T* raw to the shared pointer, which is returned.
Definition SharedPtrTypes.h:372