Re: bstr and delete[]
yufufi wrote:
mlimber wrote:
On Feb 20, 2:38 pm, yufufi <yufufi_at_comcast.net> wrote:
How does delete[] know how much memory to deallocate from the given
pointer? AFAIK this informations is put there by new[]. new[] puts the
size of the allocated memory before the just before the beginning of the
array. But I couldn't find this information by looking at the memory.
(Via VS2005 - C++)
http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.14
My second questions is, if there is a mechanism to know how much memory
is allocated for the array, why don't we use it for things like bstr?
Only thing I can think of is you may go and allocate a big chunk of
memory with new[] and use it for more then one bstr's and such. (However
i'm not even sure how you can do it with bstr since you have to use
::SysAllocString)
This part is off-topic here. Try a Microsoft group (cf. the list at
http://www.parashift.com/c++-faq-lite/how-to-post.html#faq-5.9)
Cheers! --M
The page you point to answers the question of "How many objects to
destruct?" which is a little bit different then what I'm asking.
In the sample code for one of the delete[] implementations:
You're confused. This is not a delete[] implementation-- this is a
new[] implementation. The call to operator delete[] is in a catch block
which is there to prevent a memory leak in case one of the constructor
"calls" to Fred (via placement new) fails.
// Original code: Fred* p = new Fred[n];
char* tmp = (char*) operator new[] (WORDSIZE + n * sizeof(Fred));
Fred* p = (Fred*) (tmp + WORDSIZE);
*(size_t*)tmp = n;
size_t i;
try {
for (i = 0; i < n; ++i)
new(p + i) Fred(); // Placement new
}
catch (...) {
while (i-- != 0)
(p + i)->~Fred(); // Explicit call to the destructor
operator delete[] ((char*)p - WORDSIZE);
throw;
}
'n' used to decide number of destructor calls needed. But in the line
one before the last:
operator delete[] ((char*)p - WORDSIZE);
Still compiler is presented with a pointer to an array(which in it's
first WORDSIZE has n)
1) Isn't this an infinite loop(recursive)?
No. As I already said, this is an implementation of new[] not of
delete[]. More to the point of your question, there's a distinction
between new[] and operator new[], and likewise for delete[] and operator
delete[]. The first versions not only allocate (or deallocate) memory
via operator new[] (or operator delete[]), they also construct (or
destruct) the array of objects. The second versions are basically
concerned with just low-level allocation and deallocation.
2) If the second one is somehow a different delete[], will it act like:
operator delete[] (*p)
{
arraySize = (((WORDSIZE *)p)[0])*sizeOf(Fred)
InternalDelete(p,arraySize);
}
Something like that, for an appropriately defined InternalDelete
function. It needs to free the memory allocated above by operator new[]
which was: WORDSIZE + n * sizeof( Fred).
-Mark