overloading new/delete problem
Posted
by hidayat
on Stack Overflow
See other posts from Stack Overflow
or by hidayat
Published on 2010-05-06T08:34:15Z
Indexed on
2010/05/06
8:38 UTC
Read the original article
Hit count: 224
This is my scenario, Im trying to overload new and delete globally. I have written my allocator class in a file called allocator.h. And what I am trying to achieve is that if a file is including this header file, my version of new and delete should be used.
So in a header file "allocator.h" i have declared the two functions
extern void* operator new(std::size_t size);
extern void operator delete(void *p, std::size_t size);
I the same header file I have a class that does all the allocator stuff,
class SmallObjAllocator
{
...
};
I want to call this class from the new and delete functions and I would like the class to be static, so I have done this:
template<unsigned dummy>
struct My_SmallObjectAllocatorImpl
{
static SmallObjAllocator myAlloc;
};
template<unsigned dummy>
SmallObjAllocator My_SmallObjectAllocatorImpl<dummy>::myAlloc(DEFAULT_CHUNK_SIZE, MAX_OBJ_SIZE);
typedef My_SmallObjectAllocatorImpl<0> My_SmallObjectAllocator;
and in the cpp file it looks like this: allocator.cc
void* operator new(std::size_t size)
{
std::cout << "using my new" << std::endl;
if(size > MAX_OBJ_SIZE)
return malloc(size);
else
return My_SmallObjectAllocator::myAlloc.allocate(size);
}
void operator delete(void *p, std::size_t size)
{
if(size > MAX_OBJ_SIZE)
free(p);
else
My_SmallObjectAllocator::myAlloc.deallocate(p, size);
}
The problem is when I try to call the constructor for the class SmallObjAllocator which is a static object. For some reason the compiler are calling my overloaded function new when initializing it. So it then tries to use My_SmallObjectAllocator::myAlloc.deallocate(p, size); which is not defined so the program crashes.
So why are the compiler calling new when I define a static object? and how can I solve it?
© Stack Overflow or respective owner