views:

117

answers:

1

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?

+1  A: 

You can't use the runtime library's global operator new if you provide your own. So, you can't use new to implement new, not even in initialization. Using different operator new in different source files is a violation of the one-definition rule.

Eliminate the new call from the SmallObjAllocator::SmallObjAllocator constructor, or implement a special case activated by a global bool new_uninitialized or local static bool new_is_recursing flag.

Potatoswatter