operator new/delete and class hierarchies
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);
}
}
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.
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.
精彩评论