Re: Overloading operator delete problem
kanze ha scritto:
(I'm not sure, but I think that the standard
implementation of new(nothrow) is required to use plain new, so
that just replacing plain new and plain delete should be
sufficient there.)
I could not find evidence of such guarantee. The wording just says "This
nothrow version of operator new returns a pointer obtained as if
acquired from the ordinary version." Few lines below the standard
describes the behavior by presenting a precise algorithm, so it seems to
me that default new and new(nothrow) are not intended to depend on one
another. I guess the idea was to allow this kind of implementation:
void* operator new(size_t n)
{
for(;;)
{
void* ptr = malloc(n);
if(ptr)
return ptr;
if(!_new_handler)
throw bad_alloc();
_new_handler();
}
}
void* operator new(size_t n, nothrow_t) throw()
{
for(;;)
{
void* ptr = malloc(n);
if(ptr)
return ptr;
if(!_new_handler)
return 0;
try
{
_new_handler();
}
catch(bad_alloc)
{
return 0;
}
}
}
As you can see, the try-block of new(nothrow) is entered only if
allocation fails the first time and the user provided a new-handler. On
platforms where entering a try-block have a performance hit, this could
be better than an implementation based on regular new, which would
always require entering the try-block:
void* operator new(size_t n, nothrow_t) throw()
{
try
{
return ::operator new(n);
}
catch(bad_alloc)
{
return 0;
}
}
This implies, as you pointed out, that each time an application provides
a replacement function for global operator new, it should also provide a
replacement for the nothrow version.
I find this lack of clarity an inconvenient. Maybe the standard should
specify more explicitly the relationship between new and new(nothrow) or
the lack of it. Any ideas?
Ganesh
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]