mercredi 5 avril 2017

Get address of allocated memory by pointer to a base class for non-polymorphic types

struct A {};
struct B {};
struct C : A, B {};

or

struct B {};
struct C : virtual B {};

Please note types are not polymorphic.

Having B* of dynamically allocated C*, can I get an address of allocated memory (C* in this particular case)?

This is for custom memory allocation which can be simplified to:

B* b = new(malloc(sizeof(C))) C();
// ...
// much later
// how to implement `get_allocated_ptr` for non-polymorphic types?
void* ptr = get_allocated_ptr(b);
b->~B(); // UB
free(ptr); 

I know that destructor of a base class must be virtual in this case that resolves the problem as it's possible to use dynamic_cast<void*> with polymorphic type to get address of allocated memory. I need to get allocated pointer not only to deallocate memory, but also to detect and report such non-polymorphic cases.

Aucun commentaire:

Enregistrer un commentaire