#pragma once #include #include #include #include #include namespace deepinfer { struct EnableObjectPool { bool allocated_from_object_pool_; EnableObjectPool(bool allocated_from_object_pool) : allocated_from_object_pool_(allocated_from_object_pool) {} }; template class ObjectPoolPyObject { static_assert(std::is_base_of_v); public: template py::object allocate(Args &&...args) { if (objects_.empty()) { auto obj = py::cast(new T(std::forward(args)..., true), py::return_value_policy::reference); return obj; } else { auto p = std::move(objects_.back()); objects_.pop_back(); auto ptr = p.cast(); new (ptr) T(std::forward(args)..., true); return p; } } void release(py::iterable objs) { for (auto &&obj : objs) { auto p = obj.cast(); if (p->allocated_from_object_pool_) { std::destroy_at(p); objects_.emplace_back(obj.cast()); } } } private: std::vector objects_; }; } // namespace deepinfer