Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting most derived type during object construction

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;
}
like image 807
Wells Avatar asked Oct 10 '22 09:10

Wells


1 Answers

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).

like image 119
Griwes Avatar answered Oct 12 '22 22:10

Griwes