如果一个对象在构造函数中抛出异常,基类的析构函数是否会被调用? [英] Will the destructor of the base class called if an object throws an exception in the constructor?

查看:365
本文介绍了如果一个对象在构造函数中抛出异常,基类的析构函数是否会被调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果一个对象在构造函数中抛出异常,基类的析构函数是否会被调用?

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

推荐答案

在构造期间抛出,所有先前构造的子对象将被适当地销毁。以下程序证明基础肯定被销毁:

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;
    }
}

输出:

throwing in derived constructor
destroying base


$ b b

(注意,本地指针的析构函数不做任何操作,这就是为什么我们更喜欢RAII比原始指针。)

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

这篇关于如果一个对象在构造函数中抛出异常,基类的析构函数是否会被调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆