Re: Deallocating Individual Elements of an Array Allocated Using new[]
On Jun 5, 4:49 pm, Chris Portka <chrispor...@gmail.com> wrote:
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);}
Quite right. My suggestion is explained by the fact that I thought
your main concern was related with the destruction of objects, not the
memory management. In this case, the deallocation would only take
place at the end of use of all elements inside the collection, but you
would be able to destruct any objects inside this array.
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.
Now, back to the memory problem, I recommend the use of STL list
class, if you want a collection of structures and don't want to worry
about how to manage the deallocation of each element inside it, and
these elements can be deallocated in a random way.
[]s
Wanderley Caloni
======================
http://www.cthings.org