C++ – operator new/delete and class hierarchies

c++

Suppose, we have hierarchy of classes and we want to make them allocate/deallocate their 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);  
  }  
}

Best Solution

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.