Search code examples
c++c++11placement-newvirtual-destructor

Destructor on polymorphic placed stuff


Is there a way to call destructor on objects if they are polymorphic types created with placement new?

class AbstractBase{
public:
    ~virtual AbstractBase(){}
    virtual void doSomething()=0;
};

class Implementation:public virtual AbstractBase{
public:
    virtual void doSomething()override{
        std::cout<<"hello!"<<std::endl;
    }
};

int main(){
    char array[sizeof(Implementation)];
    Implementation * imp = new (&array[0]) Implementation();
    AbstractBase * base = imp; //downcast
    //then how can I call destructor of Implementation from
    //base? (I know I can't delete base, I just want to call its destructor)
    return 0;
}

I want to destruct "Implementation" only thanks to a pointer to its virtual base... Is that possible?


Solution

  • Overkill answer: with unique_ptr and a custom deleter!

    struct placement_delete {
      template <typename T>
      void operator () (T* ptr) const {
        ptr->~T();
      }
    };
    
    std::aligned_storage<sizeof(Implementation)>::type space;
    std::unique_ptr<AbstractBase,placement_delete> base{new (&space) Implementation};
    

    Live at Coliru.