当构造函数抛出异常时,会运行什么析构函数? [英] What destructors are run when the constructor throws an exception?

查看:329
本文介绍了当构造函数抛出异常时,会运行什么析构函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中,如果构造函数抛出异常,那么运行什么析构函数?

In C++, if a constructor throws an exception, what destructors are run?

特别是,如果异常在初始化列表中,身体?

In particular, does it make any difference if the exception is during the initialization list or the body?

此外,继承和成员呢?大概所有完成的建筑都会被毁。如果只有一些成员被构造,只有那些被毁了吗?如果有多个继承,所有完成的构造函数是否被破坏?

Also, what about inheritance and members? Presumably all completed constructions get destructed. If only some members are constructed, do only those get destructed? If there is multiple inheritance, do all completed constructors get destructed? Does virtual inheritance change anything?

推荐答案

如果构造函数抛出异常,运行什么析构函数?

在该范围内完全创建的所有对象的析构函数。

Destructors of all the objects completely created in that scope.

异常是在初始化列表或正文中?

所有完成的对象都将被销毁。

如果构造函数从未完全调用对象从来没有被构造,因此不能被破坏。

All completed objects will be destructed.
If constructor was never completely called object was never constructed and hence cannot be destructed.

继承和成员呢?大概所有完成的建筑都会被毁。如果只有一些成员被构造,只有那些被毁了吗?如果有多个继承,所有完成的构造函数是否被破坏?虚拟继承是否会改变任何内容?

所有完成的结构都会被破坏。

All completed constructions do get destructed. Yes, only the completely created objects get destructed.

良好阅读:

Herb Sutter的构造函数失败

Constructor Failures by Herb Sutter

特别是,部分,他解释:

Especially, love the part where he explains:


从生物学角度看,构造函数开始了,但尽管最大的努力,一个流产 - 构造函数从未运行到期限(ination)。

In biological terms, conception took place -- the constructor began --, but despite best efforts it was followed by a miscarriage -- the constructor never ran to term(ination).

顺便说一下,这就是为什么析构函数永远不会被调用,如果构造函数没有成功 - 没有什么可以毁灭 注意,这使得短语构造函数抛出异常的对象真是一个矛盾。这样的事情甚至比以前的对象更少...它从来没有生活过,从来没有,从来没有呼吸它的第一个。

Incidentally, this is why a destructor will never be called if the constructor didn't succeed -- there's nothing to destroy. "It cannot die, for it never lived." Note that this makes the phrase "an object whose constructor threw an exception" really an oxymoron. Such a thing is even less than an ex-object... it never lived, never was, never breathed its first.

这篇关于当构造函数抛出异常时,会运行什么析构函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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