-
Notifications
You must be signed in to change notification settings - Fork 17
/
objectPool.h
62 lines (54 loc) · 1.33 KB
/
objectPool.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/*======================================================
> File Name: objectFactory.h
> Author: MiaoShuai
> E-mail:
> Other :
> Created Time: 2016年03月13日 星期日 16时28分51秒
=======================================================*/
#pragma once
#include <list>
#include <iostream>
#include <memory>
template <typename T>
class ObjectPool
{
public:
template<typename ...Args>
ObjectPool(int number,Args ...args)
:number_(number)
{
initObjectPool(args...);
}
//获取对象
T *getObject(void)
{
T *objectPtr= objectPool_.front();
objectPool_.pop_front();
return objectPtr;
}
//归还对象
void giveBackObject(T *t)
{
objectPool_.push_back(t);
}
//销毁所有对象
~ObjectPool()
{
for(auto x : objectPool_)
{
delete x;
}
}
private:
//初始化对象池
template <typename ...Args>
void initObjectPool(Args ...args)
{
for(int i = 0; i < number_; i++)
{
objectPool_.push_back(new T(args...));
}
}
std::list<T *> objectPool_;
int number_;
};