18

众所周知,如果构造函数抛出,那么所有完全构造的子对象都会以相反的顺序被销毁,包括成员数据和各种基类。但是,非委托构造函数不会调用析构函数。对于委托构造函数,当进入构造函数主体时,对象已经被构造,但构造仍在继续。因此,如果委托构造函数从其体内抛出异常,是否会调用类的析构函数?

class X
{
public:
    X();
    X(int) : X() { throw std::exception(); } // is ~X() implicitely called?
    ~X();
};
4

2 回答 2

16

规则是为所有完全构造的对象调用析构函数。一旦任何构造函数完成,包括委托的构造函数(即使程序在另一个构造函数中继续),对象就被认为是完全构造的。

于 2013-07-15T15:25:17.783 回答
7

The lifetime of an object begins when any constructor (i.e., in the case of delegation, the ultimate target constructor) is successfully completed. For the purposes of [C++03] §3.8, “the constructor call has completed” means any constructor call. This means that an exception thrown from the body of a delegating constructor will cause the destructor to be invoked automatically.

source.

And here is a nice article about delegating constructors, should anybody want to read it.

于 2013-07-15T15:26:26.990 回答