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

在 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.

相关文章