Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <memory>
- #include <vector>
- #include <type_traits>
- template<class T, uint Size>
- struct ObjectPool
- {
- using value_type = T;
- using pointer = value_type *;
- ObjectPool()
- {
- for (auto i = 1; i < Size; ++i)
- buffer[i - 1].next = &buffer[i];
- nextFreeItem = &buffer[0];
- }
- ObjectPool(const ObjectPool&) = delete;
- ObjectPool(ObjectPool&& other) noexcept
- : buffer{ std::move(other.buffer) }
- , nextFreeItem{ other.nextFreeItem }
- {
- other.nextFreeItem = nullptr;
- }
- ~ObjectPool() = default;
- template<typename U>
- struct rebind
- {
- typedef ObjectPool<U, Size> other;
- };
- template<typename U, uint other_capacity>
- ObjectPool(const ObjectPool<U, other_capacity>& other) {}
- [[nodiscard]] pointer allocate(uint size = 0)
- {
- std::cout << "ObjectPool: allocate " << size << "\n";
- if (nextFreeItem == nullptr)
- throw std::bad_alloc{};
- const auto item = nextFreeItem;
- nextFreeItem = item->next;
- return reinterpret_cast<pointer>(&item->storage);
- }
- void deallocate(pointer p, uint = 0) noexcept
- {
- std::cout << "ObjectPool: deallocate\n";
- const auto item = reinterpret_cast<Item*>(p);
- item->next = nextFreeItem;
- nextFreeItem = item;
- }
- template<typename U, typename ...Args>
- void construct(U* mem, Args&& ...args)
- {
- std::cout << "ObjectPool: construct\n";
- new (mem) value_type(std::forward<Args>(args)...);
- }
- template<typename U>
- void destroy(U* mem) noexcept
- {
- std::cout << "ObjectPool: destroy\n";
- if (mem == nullptr)
- return;
- mem->~value_type();
- //deallocate(mem, 0);
- }
- ObjectPool& operator =(const ObjectPool&) = delete;
- ObjectPool& operator =(ObjectPool&& other) noexcept
- {
- if (this == &other)
- return *this;
- buffer = std::move(other.buffer);
- nextFreeItem = other.nextFreeItem;
- other.nextFreeItem = nullptr;
- return *this;
- }
- private:
- union Item
- {
- std::aligned_storage_t<sizeof(value_type), alignof(value_type)> storage;
- Item* next;
- };
- std::unique_ptr<Item[]> buffer = std::make_unique<Item[]>(Size);
- Item* nextFreeItem = nullptr;
- };
- int main()
- {
- std::vector<int, ObjectPool<int, 5>> pool;
- pool.push_back(5);
- pool.push_back(3);
- pool.push_back(523);
- for(const auto& p : pool) {
- std::cout << p << std::endl;
- }
- pool.pop_back();
- for(const auto& p : pool) {
- std::cout << p << std::endl;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement