c++ - 多态放置的东西的析构函数

标签 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;
}

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

最佳答案

矫枉过正的答案:使用 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 .

关于c++ - 多态放置的东西的析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17845871/

相关文章:

c++ - 隐式声明的默认构造函数

c++ - C++ 中括号和逗号表达式中类型的计算顺序 (x0 = y0, x1 = y1, x2 = x0, ...)

c++ - 将字符串数组传递给函数

C++ - 向字符串添加空格

c++ - 如何使用 std::function 在谷歌测试中测试方法?

c++ - 包装 C API 以供 C++ 使用的策略

c++ - 在初始化内存上使用 placement new 是否合法?

C++ placement new vs 复制赋值

c++ - 严格的别名规则和放置新

android - 将字符串从 Java 传递到 C++ 并使用带有 NDK 案例错误的 popen?