Use boost::pool to allocate memory from a fixed size block of memory
I need to initialize chunk_size and max_alloc_size to the same value, and also provide a customized UserAllocator.
#include <boost/pool/pool.hpp> #include <iostream> #include <iomanip> struct fixed_allocator_new_delete { typedef std::size_t size_type; //!< An unsigned integral type that can represent the size of the largest object to be allocated. typedef std::ptrdiff_t difference_type; //!< A signed integral type that can represent the difference of any two pointers. static char * malloc BOOST_PREVENT_MACRO_SUBSTITUTION(const size_type bytes) { //! Attempts to allocate n bytes from the system. Returns 0 if out-of-memory static bool first_time=true; char* pblock=NULL; if(first_time) { pblock= new (std::nothrow) char[bytes]; first_time=false; } std::cout << __FUNCTION__ << "("<<std::dec<<bytes<<") return " <<std::hex<<(int)pblock <<"\n"; return pblock; } static void free BOOST_PREVENT_MACRO_SUBSTITUTION(char * const block) { //! Attempts to de-allocate block. //! \pre Block must have been previously returned from a call to UserAllocator::malloc. std::cout << __FUNCTION__<<"("<<std::hex<<(int)block<<")\n"; delete [] block; } }; int main() { boost::pool<fixed_allocator_new_delete> mypool(sizeof(int), 1000, 1000); std::cout<<"before allocation.\n"; for (int i=0; i<100*100; i++) { void* pblock=mypool.malloc(); if(!pblock) { std::cout<<"i="<<std::dec<<i<<", return null.\n"; break; } } return 0; }
0 Comments:
Post a Comment
<< Home