当构造函数抛出异常时会运行哪些析构函数?

时间:2023-04-14
本文介绍了当构造函数抛出异常时会运行哪些析构函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

在 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 的构造函数失败

特别喜欢他解释的部分:

Especially, love the part where he explains:

从生物学的角度来说,受孕发生了——构造器开始了——但尽管尽了最大的努力还是流产了——构造器从未跑到终止(化).

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.

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

上一篇:C++ - 返回码异常的参数 下一篇:为什么在异常时不调用析构函数?

相关文章