析构函数
1.什么是析构函数
析构函数于构造函数相对应,构造函数是对象创建的时候自动调用的,而析构函数就是对象在销毁的时候自动调用的的
特点:
1)构造函数可以有多个来构成重载,但析构函数只能有一个,不能构成重载
2)构造函数可以有参数,但析构函数不能有参数
3)与构造函数相同的是,如果我们没有显式的写出析构函数,那么编译器也会自动的给我们加上一个析构函数,什么都不做;如果我们显式的写了析构函数,那么将会覆盖默认的析构函数
4)在主函数中,析构函数的执行在return语句之前,这也说明主函数结束的标志是return,return执行完后主函数也就执行完了,就算return后面还有其他的语句,也不会执行的
#include <iostream> #include <string> using namespace std; class Cperson { public: Cperson() { cout << "Beginning" << endl; } ~Cperson() { cout << "End" << endl; } }; int main() { Cperson op1; system("pause"); return 0; }
执行结果:
见窗体输出结果 为准.
从这里也可以发现,此时析构函数并没有被执行,它在system之后,return之前执行
2.指针对象执行析构函数
与栈区普通对象不同,堆区指针对象并不会自己主动执行析构函数,就算运行到主函数结束,指针对象的析构函数也不会被执行,只有使用delete才会触发析构函数
#include <iostream> #include <string> using namespace std; class Cperson { public: Cperson() { cout << "Beginning" << endl; } ~Cperson() { cout << "End" << endl; } }; int main() { Cperson *op2 = new Cperson; delete(op2); system("pause"); return 0; }
执行结果:
在这里可以发现,已经出现了End,说明析构函数已经被执行,也就说明了delete触发了析构函数
3.临时对象
格式:类名();
作用域只有这一条语句,相当于只执行了一个构造函数和一个析构函数
除了临时对象,也有临时变量,例如语句int(12);就是一个临时变量,当这句语句执行完了,变量也就释放了,对外部没有任何影响,我们可以通过一个变量来接受这一个临时的变量,例如:int a=int(12);这与int a=12;不同,后者是直接将一个整型数值赋给变量a,而前者是先创建一个临时的变量,然后再将这个变量赋给变量a
#include <iostream> #include <string> using namespace std; class Cperson { public: Cperson() { cout << "Beginning" << endl; } ~Cperson() { cout << "End" << endl; } }; int main() { Cperson(); system("pause"); return 0; }
执行结果:
4.析构函数的作用
当我们在类中声明了一些指针变量时,我们一般就在析构函数中进行释放空间,因为系统并不会释放指针变量指向的空间,我们需要自己来delete,而一般这个delete就放在析构函数里面
#include <iostream> #include <string> using namespace std; class Cperson { public: Cperson() { pp = new int; cout << "Beginning" << endl; } ~Cperson() { delete pp; cout << "End" << endl; } private: int *pp; }; int main() { Cperson(); system("pause"); return 0; }
5.malloc、free和new、delete的区别
malloc不会触发构造函数,但new可以
free不会触发析构函数,但delete可以
#include <iostream> #include <string> using namespace std; class Cperson { public: Cperson() { pp = new int; cout << "Beginning" << endl; } ~Cperson() { delete pp; cout << "End" << endl; } private: int *pp; }; int main() { Cperson *op1 = (Cperson *)malloc(sizeof(Cperson)); free(op1); Cperson *op2 = new Cperson; delete op2; system("pause"); return 0; }
执行结果:
从结果上来看,只得到了一组Beginning、End说明只有一组触发了构造函数和析构函数,这一组就是new和delete