boost:pool 一实例

#ifndef LIB_MEMPOOL_HPP_
#define LIB_MEMPOOL_HPP_

 

#include <boost/pool/object_pool.hpp>

 

template <typename ObjType>
class MemPool {
public:
 virtual ~MemPool() { }

public:
 void* operator new(std::size_t n);
 void  operator delete(void* p, std::size_t n);

private:
 /*! memory pool for Object */
 static boost::object_pool<ObjType> s_obj_pool_;
};

 

 

template <typename ObjType>
boost::object_pool<ObjType> MemPool<ObjType>::s_obj_pool_;

 


#include <cstdio>
template <typename ObjType>
inline void*
MemPool<ObjType>::operator new(std::size_t n)
{
 void* p = s_obj_pool_.malloc();
 if (p) {
  return p;
 }

//不需要s_obj_pool_.construct();  思考new的重载方法!new的深入分析 

 throw std::bad_alloc();
}

template <typename ObjType>
inline void
MemPool<ObjType>::operator delete(void* p, std::size_t n)
{
 s_obj_pool_.free(reinterpret_cast<ObjType*>(p));
}

//------------------------------------------------------------------------
// Some Utilities to Ease Your Life
//------------------------------------------------------------------------
#define USING_MEMPOOL_OPERATORS(type_) /
  using MemPool<type_>::operator new; /
  using MemPool<type_>::operator delete

 

#endif // LIB_MEMPOOL_HPP_

 

使用实例:

#include "mempool.hpp"

using namespace std;

class A : public MemPool<A> {
public:
 int a;
 int b;
};

class B : public A, public MemPool<B> {
public:
 USING_MEMPOOL_OPERATORS(B);//思考为什么?using关键字 图文例解C++类的多重继承与虚拟继承
 int c;
 int d;
};

int main()
{
 A* a = new A;
 delete a;
 A* b = new B;
 delete b;
 return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值