-
-
Save gxp/f6345110847d6687b5ec to your computer and use it in GitHub Desktop.
simple object pool
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <memory> | |
| #include <vector> | |
| #include <functional> | |
| #include <iostream> | |
| template <class T> | |
| class SimpleObjectPool | |
| { | |
| public: | |
| using DeleterType = std::function<void(T*)>; | |
| void add(std::unique_ptr<T> t) | |
| { | |
| pool_.push_back(std::move(t)); | |
| } | |
| std::shared_ptr<T> get() | |
| { | |
| if (pool_.empty()) | |
| { | |
| throw std::logic_error("no more object"); | |
| } | |
| auto pin = std::unique_ptr<T>(std::move(pool_.back())); | |
| pool_.pop_back(); | |
| return std::shared_ptr<T>(pin.release(), [this](T* t) | |
| { | |
| pool_.push_back(std::unique_ptr<T>(t)); | |
| }); | |
| } | |
| bool empty() const | |
| { | |
| return pool_.empty(); | |
| } | |
| size_t size() const | |
| { | |
| return pool_.size(); | |
| } | |
| private: | |
| std::vector<std::unique_ptr<T>> pool_; | |
| }; | |
| struct A | |
| { | |
| A(){ std::cout << "A ctor" << std::endl; } | |
| ~A(){ std::cout << "A dtor" << std::endl; } | |
| }; | |
| //test code | |
| void test_object_pool() | |
| { | |
| SimpleObjectPool<A> p; | |
| p.add(std::unique_ptr<A>(new A())); | |
| p.add(std::unique_ptr<A>(new A())); | |
| { | |
| auto t = p.get(); | |
| p.get(); | |
| } | |
| { | |
| p.get(); | |
| p.get(); | |
| } | |
| std::cout << p.size() << std::endl; | |
| } | |
| int main() | |
| { | |
| test_object_pool(); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment