Poco::MemoryPool

// Library: Foundation
// Package: Core
// Module:  MemoryPool

功能:提供一个内存池,以减少new和delete的调用,提高效率,这往往是为服务端提供的。

public方法

  • void* get();
  • void release(void* ptr);
  • int allocated() const;
  • int available() const;

get 方法返回内存池中的一个内存块的地址,以对其进行操作。release则将内存块还给内存池,但并不delete。allocated()返回已经分配的内存块数,avaliable指示内存池还有多少内存块可以使用。

get可能会抛出内存池内存耗尽异常。

Poco::MemoryPool_第1张图片


demo

void MemoryPoolTest::testMemoryPool()
{
	MemoryPool pool1(100, 0, 10);
	
	assert (pool1.blockSize() == 100);
	assert (pool1.allocated() == 0);
	assert (pool1.available() == 0);
	
	std::vector<void*> ptrs;
	for (int i = 0; i < 10; ++i)
	{
		ptrs.push_back(pool1.get());
		assert (pool1.allocated() == i + 1);
		assert (pool1.available() == 0);
	}
	
	try
	{
		pool1.get();
		fail("pool exhausted - must throw exception");
	}
	catch (Poco::OutOfMemoryException&)
	{
	}
	
	int av = 0;
	for (std::vector<void*>::iterator it = ptrs.begin(); it != ptrs.end(); ++it)
	{
		pool1.release(*it);
		++av;
		assert (pool1.available() == av);
	}
	
	MemoryPool pool2(32, 5, 10);
	assert (pool2.available() == 5);
	assert (pool2.blockSize() == 32);
	assert (pool2.allocated() == 5);
}



你可能感兴趣的:(Poco::MemoryPool)