Guest User

boost pool example

a guest
Dec 11th, 2013
267
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.90 KB | None | 0 0
  1. #include <new>
  2. #include <boost/pool/singleton_pool.hpp>
  3.  
  4. class Data {
  5. public:
  6.     Data(int first) {
  7.         data[0] = first;
  8.     }
  9.    
  10.     Data(int first, int second) {
  11.         data[0] = first;
  12.         data[1] = second;
  13.     }
  14.  
  15.     void* operator new(size_t x);
  16.  
  17.     void* operator new(size_t x, const std::nothrow_t& nothrow_value) throw();
  18.  
  19.     void operator delete(void* ptr);
  20.  
  21. private:
  22.     int data[10];
  23. };
  24.  
  25. class DataTag;
  26.  
  27. typedef boost::singleton_pool<DataTag, sizeof(Data)> DataPool;
  28.  
  29. void* Data::operator new(size_t x) {
  30.     void* ptr = DataPool::malloc();
  31.     if (ptr) {
  32.         return ptr;
  33.     } else {
  34.         throw std::bad_alloc();
  35.     }
  36. }
  37.  
  38. void* Data::operator new(size_t x, const std::nothrow_t& nothrow_value) throw() {
  39.     return DataPool::malloc();
  40. }
  41.  
  42. void Data::operator delete(void* ptr) {
  43.     DataPool::free(ptr);
  44. }
  45.  
  46. int main() {
  47.     Data* data = new Data(1);
  48.     delete data;
  49.     data = new (std::nothrow) Data(1, 2);
  50.     delete data;
  51. }
Advertisement
Add Comment
Please, Sign In to add comment