Item 36. Class-Specific Memory Management MANAGEMENT
Declare that Operator New and Operator Delete members can implement category of memory allocation and management. Class Handle {public: // ... void * operator new (size_t); void operator delete (void *); //... }//...Handle * H = new handle; // buy handle: : Operator new // ... delete h; // buy handle :: operator delete
This requires overloading Operator New and Operator Delete for Handle's subclasses.
Class myHandle: public handle {// ... void * operator new (size_t); void operator delete (void *, size_t); // Note 2nd arg ///...} ;/...handle * h = New myhandle; // buy myhandle :: operator new // ... delete h; // buy myhandle :: Operator delete
-------------------------------------------------- ---- A misunderstanding concept: Using New and Delete means using the HEAP memory for the global Operator New and Operator Delete, the facts is true. Since Operator New and Operator
DELETE can be customized, so the memory allocated by the Operator New can come from the HEAP, static allocation memory block, standard capacity
The device, etc. As shown in the following example: struct rep {enum {max = 1000}; static rep * free; // Head of freelist static int num_used; // number of slots buy union {char store [sizeof (handle); rep * next; };}; static rep MEM [rep :: max]; // block of static storagevoid * handle :: operator new (size_t) {if (rep :: free) {// if Something on freelist rep * TMP = rep: : Free; // Take from free}} else} else} else} else}} else}} else}} else}} else}}} else}} else}}} else}}}}}}}}}}}}}}}}}}}}} // if slots left return & mem [rep :: Num_USED ]; // Return unused slot else // Otherwise, we're ... throw std :: bad_alloc (); // ... out of memory!} void handle :: operator delete (void * p) {// Add to freelist static_cast