看《代码大全》的时候,看到这么个问题,所以特意写代码进行了下测试。
(VC 6.0 WIN XP SP3 32BIT)
代码如下:
#include <iostream>
using namespace std;
class Test
{
public:
Test(){
// ~Test();
cout << "this is constructors." << endl;
}
~Test(){
Test();//此处调用构造函数
cout << "this is unconstructors." << endl;
}
};
void main()
{
Test test;
}
C++规定,析构函数是不能手动调用的,构造函数可以手动调用。所以,在构造函数中调用析构函数是不可取的。而在析构函数中调用构造函数则会导致无尽的对象嵌套,一直执行下去会导致内存耗尽。