Reputation: 8325
Is there a way to call destructor on objects if they are polymorphic types created with 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;
}
I want to destruct "Implementation" only thanks to a pointer to its virtual base... Is that possible?
Upvotes: 0
Views: 340
Reputation: 42584
Overkill answer: with unique_ptr
and a custom 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};
Upvotes: 3