CPPX 3.2.1
A Modern C++ Utility Library
Loading...
Searching...
No Matches
node_pool.tpp
Go to the documentation of this file.
1#pragma once
2#include "cppx/cppx.h"
3
4#include <memory>
5#include <stdexcept>
6
7namespace stl_ext
8{
9
10template <typename T> NodePool<T>::~NodePool()
11{
12 destroy_all();
13}
14
15template <typename T>
17 : m_blocks(std::move(other.m_blocks)), m_free_list(std::move(other.m_free_list))
18{
19 other.m_blocks.clear();
20 other.m_free_list.clear();
21}
22
23template <typename T> NodePool<T> &NodePool<T>::operator=(NodePool &&other) noexcept
24{
25 if (this != &other)
26 {
27 destroy_all();
28 m_blocks = std::move(other.m_blocks);
29 m_free_list = std::move(other.m_free_list);
30 other.m_blocks.clear();
31 other.m_free_list.clear();
32 }
33 return *this;
34}
35
36template <typename T> template <typename... Args> Node<T> *NodePool<T>::allocate(Args &&...args)
37{
38 void *ptr = get_slot();
39 return new (ptr) Node<T>(std::forward<Args>(args)...);
40}
41
42template <typename T> void NodePool<T>::deallocate(Node<T> *node)
43{
44 if (!node)
45 return;
46 node->~Node();
47 m_free_list.push_back(static_cast<void *>(node));
48}
49
50template <typename T> void NodePool<T>::destroy_all()
51{
52 for (auto *blk : m_blocks)
53 delete blk;
54 m_blocks.clear();
55 m_free_list.clear();
56}
57
58template <typename T> void *NodePool<T>::get_slot()
59{
60 if (!m_free_list.empty())
61 {
62 void *ptr = m_free_list.back();
63 m_free_list.pop_back();
64 return ptr;
65 }
66 if (m_blocks.empty() || m_blocks.back()->used >= Block::CAPACITY)
67 {
68 m_blocks.push_back(new Block());
69 }
70 auto &blk = *m_blocks.back();
71 void *ptr = blk.data + blk.used * sizeof(Node<T>);
72 ++blk.used;
73 return ptr;
74}
75
76} // namespace stl_ext
NodePool()=default
void deallocate(Node< T > *node)
Definition node_pool.tpp:42
NodePool & operator=(const NodePool &)=delete
Node< T > * allocate(Args &&...args)
Definition node_pool.tpp:36
Definition cppx.h:11