DOC HOME SITE MAP MAN PAGES GNU INFO SEARCH PRINT BOOK
 
Fast Special-purpose Memory Allocation for C++ - Pool(C++)

Using the Pool Class

The Pool class is declared in a header file called Pool.h, which must be included by any source program file using pools.

Allocating and freeing memory from a pool is intended to mesh well with the new and delete operators in C++. For example, suppose you have a structure called Thinglist:

   struct Thinglist {
       Thing t;
       Thinglist* next;
   };

and you want to use pools to allocate and free objects of this structure. Here is one way to do it:

   #include <Pool.h>
   

struct Thinglist { Thing t; Thinglist* next; static Pool mypool; void* operator new(size_t) { return mypool.alloc(); } void operator delete(void* p) { mypool.free (p); } };

Pool Thinglist::mypool(sizeof(Thinglist));

When a class has the new and delete operators defined, they are called to allocate and free instances of that class where possible instead of using the system memory allocator.

The argument to new is the number of bytes in an object; where inheritance doesn't enter the picture, this is always equal to the result of applying sizeof to the class and can therefore be ignored. The argument to delete is a pointer to the memory to be freed.

The only subtlety is the necessity of defining Thingpool outside the declaration of the class. This is the general rule for static class members: there must be exactly one definition of each static member in a program.

Once this is done, Thingpool automatically handles allocation for all objects of class Thing.


Next topic: Performance
Previous topic: The Pool Class

© 2005 The SCO Group, Inc. All rights reserved.
SCO OpenServer Release 6.0.0 -- 02 June 2005