It's not too clear what the question is supposed to mean. You couldjust declare a large block of stack
, and use them, perhaps using a bitvector of some sort to keep track of which ones are free or not, orsimply keeping the free elements in their own list (since you have apointer in the type). A more generic solution (not counting on thepointer) would involve a union:
union StackPoolElement{ StackPoolElement* next; double dummyForAlignment; unsigned char data[sizeof(Stack)];};static StackPoolElement pool[10000];
You can then overload operator new
and operator delete
in Stack
toallocate from this pool. (But of course, that's using new
anddelete
. Which is what makes the question so stupid; a genericsolution, which doesn't depend on the presence of a pointer in theobject, will need some form of new
to initialize the object.)
The one thing that you can't do is just declare a global byte array,since there is no guarantee that it will be correctly aligned (and I'veused more than one compiler where it wouldn't be). If you want a bytearray, it must be in some sort of a union
to guarantee sufficientalignment. (On all of the machines I know, adding a double
to theunion
is sufficient. But it's not guaranteed either.) And if you'reusing a byte array, you still need some form of new
to construct yourobjects; either you overload operator new
and operator delete
inyour class, to allocate using the byte array (and then allocateinstances of the class using new
and delete
, as normal), or you usesome form of placement new.