【发布时间】:2013-07-24 15:05:50
【问题描述】:
如果对象是使用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;
}
我只想通过指向其虚拟基础的指针来破坏“实现”...这可能吗?
【问题讨论】:
-
base->~AbstractBase(),或imp->~Implementation()。你选。 -
这甚至不是有效的 C++。你可以
delete base,它会调用派生的虚拟析构函数。您确定要在此处使用虚拟继承吗? -
是的,你是对的! ideone.com/Dv4JpO 谢谢!美化凯西的解决方案就足够了:)。
-
不能保证
array正确对齐以存储Implementation- 使用std::aligned_storage<sizeof(Implementation)>::type而不是char[sizeof(Implementation)]。 -
@Aesthete 调用
delete base将调用未定义的行为:“在第一种选择(删除对象)中,delete的操作数的值可能是空指针value,指向由先前的 new-expression 创建的非数组对象的指针,或指向表示此类对象的基类的子对象(1.8)的指针(第 10 条)。如果不是,行为未定义。” [expr.delete]/2
标签: c++ c++11 placement-new virtual-destructor