Tag:thinkinginc++ operator overload new delete
/*** book: "thinkinginc++" * Function: Reload new and delete to mimic memory allocation * Time: October 5, 2014 14:30:11* Author: cutter_point*/#include <cstddef> size_t this type of use # include <fstream> #include <iostream> #include <new>using namespace Std;ofstream out ("Framis.txt"); class framis{enum {sz=10}; static unsigned char pool[]; This force mimics the memory pool static bool alloc_map[]; This is used to mark the allocated or unallocated memory Public:enum {psize=100}; Framis () {out<< "Framis () \ n";} ~framis () {out<< "~framis () ...";} void* operator New (size_t) throw (Bad_alloc); Exception here does not say long, behind will specialize in learning void operator delete (void*);}; unsigned char framis::p ool[psize*sizeof (Framis)]; This sets the memory pool to the number of objects that can be initially stored bool Framis::alloc_map[psize]={false}; Full initialization is not assigned, falsevoid* framis::operator New (size_t) throw (Bad_alloc) {for (int i=0; i<psize; ++i) if (!allo C_map[i])//until it encounters the first block of unallocated space {alloc_map[i]=true; Mark this space has been used by return pool+ (I*sizeof (Framis)); Return to where it was assigned} out<< "Out of Memory" <≪endl; Throw Bad_alloc (); Throws an exception}void Framis::operator delete (void* m) {if (!m) return; unsigned long block= (unsigned long) m (unsigned long) pool; M minus the starting place indicates the size of the memory block/=sizeof (Framis); A total of several objects to be recycled out<< "freeing block" <<block<<endl; Alloc_map[block]=false; Recycle to reset to False}int main () {framis* f[framis::p size]; try {for (int i=0; I<framis::p size; ++i) f[i]=new Framis; New Framis; } catch (Bad_alloc) {cerr<< "Out of Memory" <<endl; } Delete f[10]; f[10]=0; framis* x=new Framis; Delete x; This will be recycled f[10], will not be recycled after 10 for (int j=0; J<framis::p size; ++j) Delete f[j]; return 0;}
"Thinkinginc++" 64, reload new and delete, to mimic the allocation of memory