C++ 单例对象池

#include

#include

using namespace std;

template 

class ObjectPool {

public:

ObjectPool() = default;

T *getObject()

{

if (vec.empty())

{

return (new T);

}

T* tmp = vec.back();

vec.pop_back();

return tmp;

}

void putObject(T *p)

{

vec.push_back(p);

}

void initialize(int cnt)

{

for (int i = 0; i < cnt; ++i) {

vec.push_back(new T);

}

}

static ObjectPool& GetInstance(int count = 0)

{

static ObjectPool instance;

if (count > 0) { instance.initialize(count); }

return instance;

}

private:

std::vector vec;

};

void main(int argc, char* argv[]) {

/**/

ObjectPool &pool = ObjectPool::GetInstance(3);

std::cout << pool.getObject() << std::endl;

std::cout << pool.getObject() << std::endl;

std::cout << pool.getObject() << std::endl;

{

auto pool = ObjectPool::GetInstance(0);

std::cout << "=========================================" << std::endl;

std::cout << pool.getObject() << std::endl;

}

/*

auto pool = ObjectPool::GetInstance(3);

错误:我发现第一次和第三次Get得到的地址是一样的。

方案:

ObjectPool::GetInstance(100);

返回的是单例的引用,类型是ObjectPool&, 左边auto推导的时候会剥去顶层的const和&,

所以第一句实际上是

ObjectPool pool = ObjectPool::GetInstance(100);

相当于把pool持有的是单例的副本,下面同理。

正确做法是:

auto &pool = ObjectPool::GetInstance(100);

*/

}

你可能感兴趣的:(C++ 单例对象池)