在构造函数中,想知道这个类是否按期望那样是否构造成功,很多人是喜欢在构造失败情况下抛出一些异常。例:
class A1
{
public:
A1()
{
pI = new int;
cout << "A1()" << endl;
{
public:
A1()
{
pI = new int;
cout << "A1()" << endl;
// something error;
throw("A1 error");
}
~A1()
{
delete pI;
cout << "~A1()" << endl;
}
private:
int *pI;
};
throw("A1 error");
}
~A1()
{
delete pI;
cout << "~A1()" << endl;
}
private:
int *pI;
};
int _tmain(int argc, _TCHAR* argv[])
{
A1 * pA1;
try{
pA1 = new A1;
}
catch(char* err)
{
cout << "A1 expection:" << err << endl;
}
return 0;
}
{
A1 * pA1;
try{
pA1 = new A1;
}
catch(char* err)
{
cout << "A1 expection:" << err << endl;
}
return 0;
}
这个程序在执行完成以后输出的结果是:
A1()
A1 expection:A1 error
可见析构函数并没有被调用,这样子的话就产生了内存泄漏。所以如果要在构造函数抛出异常之前,应该先把已经成功分配的资源释放掉,如:
A1()
{
pI = new int;
cout << "A1()" << endl;
{
pI = new int;
cout << "A1()" << endl;
// something error;
if (pI != NULL)
{
delete pI;
}
throw("A1 error");
}
throw("A1 error");
}
如果你在catch到一个类构造时异常之后,再对这个类进行析构,
try{
pA1 = new A1;
}
catch(char* err)
{
cout << "A1 expection:" << err << endl;
pA1 = new A1;
}
catch(char* err)
{
cout << "A1 expection:" << err << endl;
delete pA1;
}
}
这样的话,反而弄巧成拙,加上delete pA1会使你的程序完全崩溃。
最后,个人提议,在构造函数中不要做过多的事情,只是能对成员变量的做初始化工作就好了。真的需要做其他复杂的初始化操作,完全可以提供一个Init或Start函数.