c++ 实现对象池

c++ 简单实现一个管理对象池

ObjPool.h

#pragma once

#include 
#include 
#include 
using namespace std;

static constexpr int32_t pool_step = 3;
template
class ObjPool
{
	using shared_obj_t = shared_ptr;
	using pool_t = typename deque;
public:
	// 程序启动优先调用此函数
	static ObjPool* Instance()
	{
		static ObjPool pool;
		return &pool;
	}
	~ObjPool()
	{
		m_pool.clear();
	}
	template
	void Init(Args&&... args)
	{
		m_count += pool_step;
		for (int32_t i=0;i< pool_step;i++)
		{
			auto pObj = shared_ptr(new T(std::forward(args)...),[this](T* obj) {
				obj->Clear();
				m_pool.emplace_back(shared_ptr(obj));
				});
				m_pool.emplace_back(pObj);
		}
	}
	template
	shared_obj_t GetObj(Args&&... args)
	{
		if (m_pool.empty())
		{
			Init(args...);
		}
		auto obj = m_pool.front();
		m_pool.pop_front();
		return obj;
	}

	int32_t EmptySize()
	{
		return m_pool.size();
	}

	int32_t UseSize()
	{
		return (m_count - m_pool.size());
	}
private:
	pool_t m_pool;
	int32_t m_count{0};
};

测试代码:

#include "ObjPool.h"

class User
{
public:
	User() {}
	~User() {}
	void Clear()
	{
		cout << "clear user resource" << endl;;
	}

private:
};

class User2
{
public:
	User2() {}
	User2(const std::string& str):m_str(str) {}
	~User2() {}
	void Clear()
	{
		cout << "clear user resource" << endl;
		cout << "str ==" << m_str << endl;
	}

private:
	std::string m_str;
};

int main()
{
	auto user_pool = ObjPool::Instance();
	auto pUser = user_pool->GetObj();
	pUser = nullptr;
	cout << user_pool->EmptySize() << endl;

	auto pUser1 = user_pool->GetObj();
	auto pUser2 = user_pool->GetObj();
	auto pUser3 = user_pool->GetObj();
	auto pUser4 = user_pool->GetObj();
	cout << user_pool->EmptySize() << endl;
	cout << user_pool->UseSize() << endl;

	auto user2_pool = ObjPool::Instance();
	auto pUser5 = user2_pool->GetObj("AAAA");
	pUser5 = nullptr;
	return 0;
}

 

你可能感兴趣的:(游戏开发,c/c++)