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

前端 未结 4 769
失恋的感觉
失恋的感觉 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-08 00:04

    Yes. The rule is that every object whose constructor has finished successfully will be destructed upon exception. E.g:

    class A {
    public:
        ~A() {}
    };
    
    class B : public A {
    public:
        B() { throw 0; }
        ~B() {}
    };
    

    ~A() is called. ~B() is not called;

    EDIT: moreover, suppose you have members:

    struct A {
        A(bool t) { if(t) throw 0; }
        ~A() {}
    };
    
    struct B {
        A x, y, z;
        B() : x(false), y(true), z(false) {}
    };
    

    What happens is: x is constructed, y throws, x is destructed (but neither y nor z).

提交回复
热议问题