C++ Constructor/Destructor inheritance

后端 未结 7 2133
醉酒成梦
醉酒成梦 2020-11-30 19:10

EDIT : Summary of answers

In the following, B is a subclass of A.

It\'s a matter of terminology; ctors and dtors are not in

相关标签:
7条回答
  • 2020-11-30 19:58

    Technically, destructors ARE inherited. But in normal circumstances, the inherited destructors are not directly used for a derived class; they're invoked because the derived class's own destructor calls them in order to destroy its own "base class subobjects" as a step within destroying the larger object. And in the unusual circumstances where you do directly use a base class destructor on a derived object, it's very difficult to avoid Undefined Behavior.

    This example comes straight from the C++ Standard (12.4p12).

    struct B {
      virtual ~B() { }
    };
    struct D : B {
      ~D() { }
    };
    
    D D_object;
    typedef B B_alias;
    B* B_ptr = &D_object;
    
    void f() {
      D_object.B::~B();              // calls B's destructor
      B_ptr->~B();                   // calls D's destructor
      B_ptr->~B_alias();             // calls D's destructor
      B_ptr->B_alias::~B();          // calls B's destructor
      B_ptr->B_alias::~B_alias();    // calls B's destructor
    }
    

    If ~B were not an inherited member of D, the first statement in f would be ill-formed. As it is, it's legal C++, though extremely dangerous.

    0 讨论(0)
提交回复
热议问题