Getting the most derived type when building an object

In my project, I have a base base class Base. I would like to track all the dynamic allocation / release of objects that come from the "Base". To do this, I redefined the new / delete operators in "Base".

After successfully allocating memory in an overridden new statement, I would like to notify the object that I use to track the memory that the allocation has occurred, with the most derived allocation type and size. Size is not a problem (since it was passed directly to the new operator for "Base"), but the problem with the most derived type is a problem.

I tend to think that this is not possible in the way I try to do this. Since the more derivative parts of the object have not yet been built, there is no way to know what they are. Nevertheless, the overloaded new operator of the "Base" class knows something about the final product - size - so can you find out something else?

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;
}
+5
source share
2 answers

You are right, this is impossible, since the operator newsimply allocates memory, nothing more. The right place for this is the constructor, not the dispenser, where you can use RTTI to determine the type of inline object (and therefore it can be done in the constructor Base, and not in every constructor of the child class).

+2

, GC ++. , .

struct base {
   void *operator new(size_t sz) {
     // ...
   }
};

struct init_tag {};

base * operator % (init_tag, base *ptr) {
  // just do what you like here...
  return ptr;
}

#define gc_new init_tag() % new
+2

All Articles