看看C++语言标准,有没有办法只调用派生类的析构函数,而不调用基类的析构函数?
所以,对于类
class Base { public: virtual ~Base() {} };
class Derived : public Base { public: ~Derived();};
如果可以这样写代码
Base *basePtr = new Derived();
//do something with basePtr
// Now somehow destroy Derived while keeping Base - call ~Derived() only,
// line below however will call both ~Derived() and ~Base() - how it can be done?
dynamic_cast<Derived*>(basePtr)->~Derived();
因此,在执行完上面的代码之后,basePtr 将仅指向 Base 对象,就像它是由以下人员创建的一样
Base *basePtr = new Base();
加上在调用 new Derived() 和销毁 Derived 类之间操作 basePtr 导致的对 Base 对象的任何修改?
或者,这是被禁止的并且是不可能的吗?
最佳答案
不,这是不可能的。该标准要求销毁 Derived 对象会销毁整个对象,包括 Base 子对象。根据 C++ 对对象生命周期的理解,其他任何东西都不是破坏。
根据你想实现的,考虑先把base复制出derived
std::unique_ptr<Base> basePtr(new Derived());
//do something with basePtr
basePtr.swap(std::unique_ptr<Base> (new Base(*basePtr))); //splice the Base part out of the derived object
//basePtr now points to the spliced Base object.
另一种方法是在 boost::optional
(或只是一个 pimpl)中保留 derived 的额外成员,并重置它以获得一个“剥离”的 Derived 对象,该对象仍然有它的 Base类部分。然而,这不会影响虚函数调度。
关于c++ - 仅调用派生类的析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15883582/