Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to call the destructor without knowing the type?

Is it possible to call the destructor of an object without knowing the class type without using delete? I am asking because I am working on an allocator (for fun/ practice) and I am using malloc/ placement new to constructor the object but then when I go to destruct the object, I was curious if there was a way to do so without knowing the type. If it is not possible, why not? Is it the only way to do is the way I show in my sample code (that is commented out)?

#include <stdio.h>
#include <new>

void* SomeAllocationFunction(size_t size) {
    return malloc(size);
}

class SomeClass{
public:
    SomeClass() {
        printf("Constructed\n");
    }

    ~SomeClass() {
        printf("Destructed\n");
    }
};

int main(void){
    void* mem = SomeAllocationFunction(sizeof(SomeClass));
    SomeClass* t = new(mem)SomeClass;

    free(t);
    //t->~SomeClass(); // This will call the destructor, is it possible to do this without knowing the class?

    return 0;
}

(I know I can just call delete, but please ignore that for the moment.)

like image 778
mmurphy Avatar asked Nov 25 '25 06:11

mmurphy


2 Answers

No, it's not possible without knowing the type (or knowing one of the object's base types that has a virtual destructor).

Typically speaking, custom allocators neither construct nor destruct the object, though some make a templated wrapper around the allocator that performs a placement new or a direct destructor call.

(Technically, you could associate with every allocation a function pointer that ends up calling the type's destructor. But that's fairly sketchy, and I wouldn't recommend it.)

like image 55
John Calsbeek Avatar answered Nov 27 '25 20:11

John Calsbeek


No, you can't call the destructor without knowing the class, because the compiler doesn't know which destructor to call. You could either:

  • Make all objects inherit from some base object that has a virtual destructor, and use that base object pointer instead of a void pointer
  • Make use of templates
  • Have the allocator itself not manage the calling of constructors/destructors
like image 35
slartibartfast Avatar answered Nov 27 '25 18:11

slartibartfast



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!