Re: Deallocating Individual Elements of an Array Allocated Using new[]
If I understood your target, and think the best method for what you
looking for would be to use the placement new, i.e., creating all the
objects you need inside a preallocated area of memory. After that,
instead of deallocating the memory, you just need to call the
destructor for the objects you need to dismiss. I assuming you using
this technique with a real object, not primitive types.
Yes, you are correct and this was my intuition - preallocating memory
somehow. However I'm slightly confused by your suggestion to just
call the destructor for objects I need to dismiss. I thought that
calling the destructor does not actually free the memory associated
with the object - my understanding is that delete gets transformed as
such:
delete obj; --> compiles to...
if (obj != NULL) {
obj->~Object();
operator delete(obj);
}
So if the destructor doesn't free anything, then I have to explicitly
free the preallocated memory array anyway - why waste time calling the
destructor when I can just call delete[] for the entire array? The
overall goal is to avoid an additional messy data structure that would
have to keep track of all the new[]'s for preallocated memory, detect
when all the objects were finished, and safely call delete[] for the
preallocated memory. It looks as though C++ does not offer a way to
avoid this unless what you're saying about the destructor actually
frees the memory from the preallocated array.
unsigned char myMem[sizeof(MyClass) * 1000);
MyClass* pMyObjects = new (myMem) MyClass[1000];
...
pMyObjects[0].~MyClass();
...
pMyObjects[1].~MyClass();
...
pMyObjects[2].~MyClass();
...
...
pMyObjects[999].~MyClass();
[]s