c++ - 仅调用派生类的析构函数

标签 c++ inheritance casting type-conversion

看看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/

相关文章:

字符数组到无符号短转换问题

java - 我可以更改抽象类中变量的类吗

c++ - cpp 中的嵌套对象创建。下面伪代码中的函数调用顺序是什么?

c++ - 我可以从initializer_list实例化一个数组吗?

c++ - operator= 和 C++ 中不继承的函数?

c - 从没有强制转换的整数生成指针... DS1307、RTC、BCD

c++ - 从字符串执行 Lua 函数

C++ 为类中未初始化的变量启用警告

c++ - 继承函数返回派生类,而不是基类

c - C 中的结构继承限制