多态放置的东西的析构函数

Destructor on polymorphic placed stuff

本文关键字:析构函数 多态      更新时间:2023-10-16

如果对象是用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;
}

我只想通过指向其虚拟基础的指针来破坏"实现"。。。这可能吗?

Overkill答案:使用unique_ptr和自定义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};

住在科利鲁。