多态放置的东西的析构函数
Destructor on polymorphic placed stuff
如果对象是用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;
}
我只想通过指向其虚拟基础的指针来破坏"实现"。。。这可能吗?
Overkill答案:使用unique_ptr
和自定义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};
住在科利鲁。
相关文章:
- 如何正确取消析构函数中的 Boost deadline_timer(在多线程环境中)?
- C++使用函数对象的线程,如何调用多个析构函数而不是构造函数?
- Singleton模式中的手动析构函数调用:调用多次
- C++ - 析构函数的调用次数比预期的多
- 何时使用多个函数调用和 QTimer 调用析构函数?
- 为什么在将多态行为与指向接口的指针一起使用时没有调用析构函数?
- 对象析构函数在多线程处理时不断被调用,但该对象并未超出范围
- 对象计数复制构造函数的调用次数比析构函数多
- 不是多态类型,或者为什么我们在这里需要虚拟析构函数?
- 具有纯虚函数析构函数的多态C++
- 设计一个没有虚拟析构函数的多态类层次结构
- 多态类中的虚拟析构函数
- c++在没有虚拟析构函数的多态性中共享ptr
- 在多态性中调用3层析构函数
- 多态类的隐式析构函数是否可以成为虚拟的
- Clang & GCC 在使用智能指针时不会警告非虚拟基析构函数的多态性?
- 多态放置的东西的析构函数
- 多态性=资源泄漏中基类缺少虚拟析构函数
- 基类析构函数中虚函数调用的多态能力
- 非多态基类中的析构函数