其他分享
首页 > 其他分享> > c – 具有虚析构函数的基类的子类中的默认析构函数

c – 具有虚析构函数的基类的子类中的默认析构函数

作者:互联网

我有一个带有虚拟析构函数的基类A. A有后代B和C,它们使用默认的析构函数.通过指向A的指针删除C的对象是否安全?

更具体地说,请考虑以下示例代码:

class A {
 public:
      A(){};
      virtual ~A() {/* code here */};
 };
 class B: public A {
      B() {/* code....*/};
      /* NO DESTRUCTOR SPECIFIED */
   };
 class C: public B {/*same as above, no destructor */};
 class D: public B {/* same as above, no destructor*/}

要运行的代码如下所示:

A* getAPointer(void); /* a function returning a C or a D*/
A* aptr=getAPointer();
/* aptr is declared as A*, but points to either an object of class C 
  or class D*/
delete aptr;

删除aptr安全吗?它做了正确的事情:如果aptr指向C类的对象,aptr首先调用C的析构函数,然后是B的析构函数,最后是A的析构函数?

解决方法:

Is it safe to delete an object of C through a pointer to A?

是的,它是完全安全的,因为B,C和D类中的所有析构函数都将是隐式虚拟的.

从:

15.4 Destructors [class.dtor]

10 A destructor can be declared virtual (13.3) or pure virtual (13.4);
if any objects of that class or any derived class are created in the
program, the destructor shall be defined. If a class has a base class
with a virtual destructor, its destructor (whether user- or
implicitly-declared) is virtual.

由于A具有虚拟析构函数,因此B和C,D分别具有虚拟析构函数和:

delete aptr;

工作正常.

标签:virtual-destructor,c
来源: https://codeday.me/bug/20190823/1697923.html