New / delete operators and class hierarchies
Suppose we have a hierarchy of classes and we want them to allocate / free memory only throughout our entire memory manager. What is the classic C ++ way to achieve this behavior? Should it have additional checks like:
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);
}
}
+2
source to share
2 answers
No verification needed.
Have a look at the Alexandrescu Loki SmallObject Allocator , you just inherit from SmallObject and it all does the heavy lifting for you!
And don't forget to overload all versions of new and delete:
- simple version
- array version
- placement version
Otherwise, you may have problems.
+2
source to share
my comments:
make the creators do something like:
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 can extend the creator to check for memory leaks, or use a memory pool to manage your objects, etc.
0
source to share