mmurphy
mmurphy

Reputation: 1347

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.)

Upvotes: 3

Views: 1022

Answers (4)

Bart
Bart

Reputation: 1580

As of C++17 this has become possible with std::destroy_at. See CPP Reference.

Upvotes: 1

John Calsbeek
John Calsbeek

Reputation: 36497

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.)

Upvotes: 2

Nicol Bolas
Nicol Bolas

Reputation: 473352

It is no more possible to call the destructor on an untyped piece of memory than it is to call a constructor (ie: placement new) without a type. Both the constructor and the destructor are part of the object, and the compiler needs a type to know what to call.

Upvotes: 2

slartibartfast
slartibartfast

Reputation: 4428

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

Upvotes: 2

Related Questions