I have a very large, spread out class that is essentially a very contrived two dimensional linked list. I want to be able to “compile” it, by which I mean I want to finalize the list, so that only read accesses may be made, and then move all the elements into contiguous memory spaces. My rough solution is this:
#include <new>
...
MyListNode* pool = new MyListNode[length];
new(&pool[position]) MyListNode();
The trouble is that I essentially have two classes, one allocated with new and the other allocated with this method up here, and when I try to delete any of the objects allocated by the above method, glibc kills the program because of an invalid pointer.
The natural solution is to create two classes, and just use runtime polymorphism to provide one interface but two implementation, etc. Is there any way that the memory standard in C++ permits this kind of jiggery pokery?
Are you calling
deleteon one of the objects in your array? Or are you manually invoking the destructor to mirror the placement new?Since you have one call to non-placement new, you should only have one call to delete. And since you have n-calls to placement-new, you should manually invoke the destructor n times.
So, you may want something like this: