In my project, I have an abstract base class "Base". I would like to track all of the dynamic allocations/deallocations of objects that derive from "Base". To this end, I've overridden the new/delete operators in "Base".
After successfully allocating memory in the overridden new operator, I'd like to notify the object I'm using for tracking memory that an allocation has occurred, with the most derived type of the allocation and it's size. The size isn't a problem (as it's passed directly in to the new operator for "Base"), but getting at the most derived type is an issue.
I'm leaning towards thinking this isn't possible in the way I'm trying to do it. Since the more derived parts of the object haven't been constructed yet, there's no way to know what they are. However, the "Base" class' overloaded new operator knows something about the final product- the size- so is it possible to know anything else about it?
For context:
void* Base::operator new( size_t size )
{
void* storage = malloc( size );
if ( storage == NULL )
throw std::bad_alloc();
// Notify MemoryTracker an allocation has occurred
// MemoryTracker::Instance().Allocate( type, size );
return storage;
}
You're right, it's not possible this way, as new
operator just allocates memory, nothing more. The right place to do such thing is constructor, not allocator, where you should be able to use RTTI to determine type of built object (and thus it can be done in Base
constructor, not in every child class constructor).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With