2013-07-24 22 views
0

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

我想仅仅通过指向它的虚拟基地来破坏“实施”......这可能吗?

+6

'base->〜AbstractBase()',或'imp->〜Implementation()'。你选。 – Casey

+3

这甚至不是有效的C++。你可以'删除基地',这将调用派生的虚拟析构函数。你确定你想在这里使用虚拟继承吗? – Aesthete

+0

是的,你是对的! http://ideone.com/Dv4JpO谢谢! Esthete从凯西的解决方案是足够的:)。 – GameDeveloper

回答

3

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

+0

我认为你应该将alignment作为第二个参数提供给'aligned_storage'。虽然这似乎不是必需的。 – dyp

+1

例如:'std :: aligned_storage :: type' – dyp

+0

lol!您阅读我的想法我需要的是与unique_ptr删除器一起使用Casey:p – GameDeveloper