全面解析C++中的析构函数
“析构函数”是构造函数的反向函数。在销毁(释放)对象时将调用它们。通过在类名前面放置一个波形符 (~) 将函数指定为类的析构函数。例如,声明 String 类的析构函数:~String()。 // spec1_destructors.cpp #include <string.h> class String { public: String( char *ch ); // Declare constructor ~String(); // and destructor. private: char *_text; size_t sizeOfText; }; // Define the constructor. String::String( char *ch ) { sizeOfText = strlen( ch ) + 1; // Dynamically allocate the correct amount of memory. _text = new char[ sizeOfText ]; // If the allocation succeeds,copy the initialization string. if( _text ) strcpy_s( _text,sizeOfText,ch ); } // Define the destructor. String::~String() { // Deallocate the memory that was previously reserved // for this string. if (_text) delete[] _text; } int main() { String str("The piper in the glen..."); } 在前面的示例中,析构函数 String::~String 使用 delete 运算符来动态释放为文本存储分配的空间。
使用构造函数 当下列事件之一发生时,将调用析构函数: 析构函数可以随意调用类成员函数和访问类成员数据。从析构函数调用虚函数时,调用的函数是当前正在销毁的类的函数。 // order_of_destruction.cpp #include <stdio.h> struct A1 { virtual ~A1() { printf("A1 dtorn"); } }; struct A2 : A1 { virtual ~A2() { printf("A2 dtorn"); } }; struct A3 : A2 { virtual ~A3() { printf("A3 dtorn"); } }; struct B1 { ~B1() { printf("B1 dtorn"); } }; struct B2 : B1 { ~B2() { printf("B2 dtorn"); } }; struct B3 : B2 { ~B3() { printf("B3 dtorn"); } }; int main() { A1 * a = new A3; delete a; printf("n"); B1 * b = new B3; delete b; printf("n"); B3 * b2 = new B3; delete b2; } 输出: A3 dtor A2 dtor A1 dtor B1 dtor B3 dtor B2 dtor B1 dtor 虚拟基类 演示虚拟基类的继承关系图
为了确定 E 类型的对象的虚拟基类的析构顺序,编译器将通过应用以下算法来生成列表:
因此,对于 E 类,析构顺序为:
此过程将生成唯一项的有序列表。任何类名均不会出现两次。在构造列表后,将以相反的顺序遍历该列表,并且将调用列表中每个类(从最后一个到第一个)的析构函数。 如果某个类中的构造函数或析构函数依赖于要先创建或保留更长时间的另一个组件(例如,如果 A 的析构函数(上图中所示)依赖于执行其代码时仍存在 B),则构造或析构的顺序特别重要,反之亦然。 class MultInherit : public Base1,public Base2 ... 在前面的示例中,先于 Base2 的析构函数调用 Base1 的析构函数。 s.String::~String(); // Nonvirtual call ps->String::~String(); // Nonvirtual call s.~String(); // Virtual call ps->~String(); // Virtual call 可以使用对前面显示的析构函数的显式调用的表示法,无论类型是否定义了析构函数。这允许您进行此类显式调用,而无需了解是否为此类型定义了析构函数。显式调用析构函数,其中未定义的析构函数无效。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |