tags:

views:

144

answers:

2

hello.

suppose,we have hierarchy of classes and we want to make them allocate/deallocate theirs memory only throughout our memory manager. what is a classical C++ way to achieve this behavior? is it a MUST* to have additional checks such as:

 class Foo{  
  public:  
  virtual ~Foo(){}  
  void* operator new(size_t bytes)  
  {  
    if (bytes != sizeof(Foo)){  
        return ::operator new(bytes);
    }    
    return g_memory_manager.alloc(bytes);  
  }  
  void operator delete(void *space, size_t bytes)  
  {  
    if (bytes != sizeof(Foo)){  
        return ::operator delete(space);  
    }  
    g_memory_manager.dealloc(space, bytes);  
  }  
}

thanks for help.

A: 

my comments:

make creators to do the things, for example:

template<class t>
struct creator_new { // a creator using new()/delete()
    static t *Create(void) 
    {
        return new t;
    }
    static void Destroy(t *p) 
    {
        delete p;
    }
};

you could extend the creator to check memory leak, or use memory pool to manage your objects etc.

EffoStaff Effo
But the possibility to overloading `new` and `delete` was added to C++ in order to prevent users from having to change several 100kLoC just to test whether a custom allocator would improve performance. Also, sometimes it's not possible to change the code. (Because it might be code of your customers.) With overloading you can do this with only introducing the two functions in one class and without having to touch any user code.
sbi
+2  A: 

No the checks are unnecessary.

Have a look at Alexandrescu's Loki's SmallObject allocator, you just inherit from SmallObject and it does all the heavy lifting for you!

And do not forget to overload all versions of new and delete:

  • simple version
  • array version
  • placement version

Otherwise you might have some troubles.

Matthieu M.
thanks to everyone for clarifications.
varnie
How in the world can these checks be unnecessary?
sbi
Oh wait, I guess I know what you mean: These checks are unnecessary if (and only if) the allocator used can deliver arbitrary sized chunks of memory. I was working from the assumption that a class-specific allocator would deliver only chunks of one size, because that's what makes it possible to implement very fast allocation/deallocation. Now, looking at varnie's code, I see that his allocator takes a size argument, so that restriction doesn't seem to apply.
sbi
Yes, the idea is that new receives the size anyway, you can use multiple pools of various sizes and select the better fit.
Matthieu M.