In the following program, I got runtime error (program hangs) from template <typename T>
MemoryPool<T>::~MemoryPool(). I suspect that it has something to do with the reinterpret_cast that is used in the contructor. Can some one help by pointing out how to fix it? Thanks in advance.
EDIT: sorry, I did not post complete program above (now two line methods added to it). Here is more of it (please note: it is still not a complete implementation, but should give an idea of the problem)
Since you don't appear to be constructing the MemoryPool<T> objects (you are not calling their constructors), you cannot delete[] them using a pointer of that type. You must delete[] using a char pointer.
Change
delete [] nextPtr;
to
delete [] reinterpret_cast<char*>(nextPtr);
Otherwise it tries to delete array of MemoryPool<T> calling destructors for each object of the array. Meantime there is no array of MemoryPool<T>. It is array of char-s.
This code uses uninitialized objects. There is no placement new calls on allocated memories. Why don't you use std::list?
agile, thank you very much. Your suggestion works and your explanation makes perfect sense. Yes, I did not contruct the MemoryPool<T> objects so I can not delete [] nextPtr in the dtor. The code was taken from a book that I wanted to throw away because this code did not compile. Now I pick it up again.
The trickest thing in the book for me is the aftermentioned struct NextOnFreeList as another implementation of a memory pool. Its first few bytes are used as next pointer in a linked list. Yet it actually contains a list of Rational objects. In other words, the struct NextOnFreeList "have a dual role as a sequence of Rational objects as well as a sequence of NextOnFreeList element". I do not fully understand what is going on with the reinterpret_cast<> under the hood. Can some one help explain it?