C++编程语言可以被看做是C语言的升级版本,它的许多应用方法都与其他编程语言有相似之处。不过在一些特定的使用方法中,还是有些不同的应用方式。在这里我们就先来了解一下C++析构函数的一些特殊应用方式。
C#中的终结器(也就是析构函数)类似于C++析构函数,但是由于编译时无法确定终结器的执行时机,因此两者实际上存在相当大的区别。垃圾回收器调用C#终结器的时机是在对象上一次使用之后,但是在应用程序关闭之前的某个时间。相反,只要一个对象(而非指针)超出范围,(此处的范围指作用域),就会自动调用C++析构函数。对此我还真有点怀疑,于是分别写了C++与C#的代码看一下情况是否真的是这样。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
test();
}
static void test()
{
myPeople p = new myPeople();
Console.WriteLine("Complate");
}
}
class myPeople
{
public myPeople()
{
Console.WriteLine("Construct");
}
~myPeople()
{
Console.WriteLine("Dispose");
}
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
于是我分别在各个方法中插入断点然后F5开始逐步调试,我发现没有myPeople的调用是在test()方法执行完毕后,Main()方法结束执行器调用的。再看C++
#include<iostream>
#include<string>
using namespace std;
class myPeople
{
public :
myPeople()
{
cout<<"Construct"<<std::endl;
}
~myPeople()
{
cout<<"Dispose"<<std::endl;
}
};
void myMethod()
{
myPeople my;;
cout<<"Complate"<<std::endl;
}
int main()
{
myMethod();
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
通过上面的执行过程就会发现确实如同本质论作者说的那样,C#调用终结器与C++析构函数区别是相当大的。C#清理一个类的资源并不是确定的,而C++类资源的释放是该类超出作用域之后便开始调用析构函数。
【编辑推荐】