开发者

Getting most derived type during object construction

开发者 https://www.devze.com 2023-03-23 20:29 出处:网络
In my projec开发者_运维知识库t, 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 ove

In my projec开发者_运维知识库t, 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).


There is a trick for this I learnt when studying GC implementations for C++. A downside is that you must use a macro instead of plain new.

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
0

精彩评论

暂无评论...
验证码 换一张
取 消