What happens to base class destructor if a derived class destructor throws an exception

后端 未结 3 1642
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-08 20:09

It just happened to me I wondered how resources are freed in the following case.

class Base {
  Resource *r;

public:
  Base() { /* ... */ }
  ~Base() {
             


        
3条回答
  •  萌比男神i
    2020-12-08 21:12

    The base class destructor is indeed called. Sample code:

    #include 
    #include 
    
    class Base {
    public:
      Base() { /* ... */ }
      ~Base() {
        printf("Base\n");
      }
    };
    
    class Derived : public Base {
    public:
      Derived() { /* ... */ }
      ~Derived() {
        printf("Derived\n");
        throw 1;
      }
    };
    
    int main() {
      try {
        Derived d;
      } catch(...) {
        printf("CAUGHT!\n");
      }
    }
    

    This prints:

    Derived
    Base
    CAUGHT!
    

提交回复
热议问题