Re: overloading operator delete[](void*, size_t) - possibly incorrect implementation of the language specification in Visual C++?
On Thu, 16 Dec 2010 16:24:25 CST
Dobi <harry@daiw.de> wrote:
On 16 Dez., 12:19, Neil Butterworth <nbutterworth1...@googlemail.com>
wrote:
On Dec 14, 7:54 pm, Dobi <ha...@daiw.de> wrote:
should s be equal in the call of new[] and in the call of delete[]
in the following example, as it is with g++?
With MSVC++2010 (and 2005) it is not.
#include <iostream>
using namespace std;
class C {
public:
int j;
void* operator new[]( size_t s ) {
cout << "new[]: size_t=" << s << endl;
return ::operator new[]( s );
}
void operator delete[]( void* ptr, size_t s ) {
cout << "delete[]: size_t=" << s << endl;
}};
int main() {
C* x = new C[100];
delete[] x;
return 0;
}
Is this an incorrect implementation of the language specification
in Visual C++ or am I overlooking something?
The standard says, in 12.5/5:
"When a delete-expression is executed, the selected deallocation
function shall be called with the address of the block of storage
to be reclaimed as its first argument and (if the two-parameter
style is used) the size of the block as its second argument."
There is nothing that says that the block has exactly the size you
asked for in the call to new.
Neil Butterworth
Thanks for the answer. It looks like I have to take care by myself to
save the array size (for example in the first size_of(size_t) bytes of
my memory block) to be able to deallocate correctly.
Some research showed, that in Alexandrescu's Loki this is
functionality is disabled with help of the precrocessor for Microsoft
compilers. I think I will to the same. Additionally it is quite odd,
that VC++'s standard new[] uses the first size_of(size_t) bytes of the
memory for storing the number of elements in the array only if the
element (or one of its members or members members...) has a non-empty
destructor.
This approach surely can't be right, as the two argument version of
operator delete[] is obliged to provide the size of the block to be
deallocated.
Presumably what has happened is that to maintain an optimised heap
layout, the call to operator new[] returned more memory than
requested. In that case, you would need to delete the memory
allocated, not the memory requested as you propose.
I doubt very much that microsoft's compilers are as wayward as you
suggest.
Chris
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]