Will the destructor of the base class called if an object throws an exception in the constructor?

前端 未结 4 869
失恋的感觉
失恋的感觉 2021-01-07 23:08

Will the destructor of the base class be called if an object throws an exception in the constructor?

4条回答
  •  天命终不由人
    2021-01-07 23:54

    When an exception is thrown, the destructors are called for all (sub-) objects whose constructors were successfully run. This extends to data members and base classes alike.

    For example, for this code

    struct base {};
    
    struct good {};
    
    struct bad {
      bad() {throw "frxgl!";}
    };
    
    struct test : public base {
      std::string s;
      good g;
      bad b;
      test() {}
    };
    

    before test's constructor is executed, first the constructor for the base class is called, then the constructors for s, g, and b. Only if these finish successfully, the constructor for test is executed. When the exception is thrown during the construction of b, the base class constructors as well as the constructors for the data members s and g have been fully executed, so their destructors are run. The constructor of test itself and of b have not been run successfully, so their destructors are not run.

提交回复
热议问题