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

时间:2013-07-24 22:26:30

标签: c++ c++11 placement-new virtual-destructor

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

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

1 个答案:

答案 0 :(得分:3)

Overkill answer:使用unique_ptr和自定义删除器!

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