您的位置:首页 > 编程语言 > C语言/C++

C++构造函数和析构函数的调用顺序

2014-03-16 11:00 288 查看
析构函数的调用顺序是从底往上的:

[1] first, the constructor invokes its base class constructors,

首先,是调用该类的基类构造函数

[2] then, it invokes the member constructors, and

然后是该成员类的构造函数(重要记忆,有些书好像没有提到)

[3] finally, it executes its own body.

最后才是本类的构造函数

而析构函数的调用顺序刚好是相反

A destructor ‘‘tears down’’ an object in the reverse order:

[1] first, the destructor executes its own body,

首先调用本类的析构函数

[2] then, it invokes its member destructors, and

然后调用成员类的析构函数

[3] finally, it inv okes its base class destructors.

最后才是基类的析构函数

特别指出:虚基类是在其他任何类之前调用构造函数的,而在所有其他类之后调用析构函数的。

这样的调用顺序是为了保证基类或者成员类没有在他们创建之前被调用,或者在析构之后还可能被调用。

构造函数根据声明顺序,执行成员类和基类的构造函数,而不是根据初始化列表(initializers)顺序。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: