object_pool物件池

object_pool是用於類例項(物件)的記憶體池,它能夠在析構時呼叫所有已經分配的記憶體塊呼叫解構函式,從而正確釋放資源,需要包含以下標頭檔案:

#include <boost/pool/object_pool.hpp>
using namespace boost;

其中最關鍵的是construct()destroy()函式,這兩個函式是object_pool的真正價值所在。construct()實際上是一組函式,有多個引數的過載形式(目前最多支援3個引數,但可以擴充套件),它先呼叫malloc()分配記憶體,再在記憶體塊上使用傳入的引數呼叫類的建構函式,返回的是一個已經初始化的物件指標。destory()則先呼叫物件的解構函式,再用free()釋放記憶體塊。

用法

可以直接使用construct()直接在記憶體池中建立物件

struct demo_class
{
int a,b,c;
string str = "hello boost"; demo_class(int x = 1, int y = 2, int z = 3):a(x), b(y), c(z)
{
cout << "created a demo_class object." << endl;
}
~demo_class()
{
cout << "destroyed a demo_class object." << endl;
} }; int main()
{
// 物件記憶體池
object_pool<demo_class> op; // 傳遞引數構造一個物件
auto p = op.construct(4, 5, 6); cout << p->a << "\n"
<< p->b << "\n"
<< p->c << "\n"
<< p->str << "\n"
<< endl; // 連續分配大量物件
for (int i = 0; i < 10 ; i++)
{
auto p = op.construct(4, 5, 6);
}
cout << "at the end of the main function.\n" << endl; }