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

前端 未结 4 847
失恋的感觉
失恋的感觉 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:06

    If an exception is thrown during construction, all previously constructed sub-objects will be properly destroyed. The following program proves that the base is definitely destroyed:

    struct Base
    {
        ~Base()
        {
            std::cout << "destroying base\n";
        }
    };
    
    struct Derived : Base
    {
        Derived()
        {
            std::cout << "throwing in derived constructor\n";
            throw "ooops...";
        }
    };
    
    int main()
    {
        try
        {
            Derived x;
        }
        catch (...)
        {
            throw;
        }
    }
    

    output:

    throwing in derived constructor
    destroying base
    

    (Note that the destructor of a native pointer does nothing, that's why we prefer RAII over raw pointers.)

提交回复
热议问题