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.)
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.)
No, you can't call the destructor without knowing the class, because the compiler doesn't know which destructor to call. You could either:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With