今天搞了一个异常类,有一个char *desc 成员,是在对象创建时动态分配的.在外部的catch语句中
总是被释放掉.而另一个成员 int code 确是正确的.
后来经过研究发现,是缺少一个复制构造函数,加了红色部分就ok了.异常对象在throw语句到catch的
传递过程中要进行对象复制,像有指针成员这种情况,如果没有自己定义的复制构造函数,复制的对象
和throw语句的对象指针成员指向同一块内存.默认的复制过程完成后throw语句会调用析构函数会把
内存释放掉,这样catch语言中的异常对象指针成员就会出错了. 自定义一个复制构造函数如下就可以避免
这种情况.
/************************************************************************/
/* 异常定义 */
/************************************************************************/
#ifndef _PDF_CEXCEPTION_
#define _PDF_CEXCEPTION_
#define PE_ENCRIPTED 0x01
#define PE_PARAMETER_ERROR 0x02
#define PE_PARSE_ERROR 0x03
class CPdfException
{
public:
CPdfException(char *except_desc,int except_code );
CPdfException(CPdfException &);
~CPdfException();
void debug_print();
protected:
private:
char *desc;
int code;
};
/************************************************************************
* 异常实现
************************************************************************/
#include <string.h>
#include <stdio.h>
#include "CPdfException.h"
CPdfException::CPdfException(char *except_desc,int except_code )
{
int len = strlen(except_desc);
desc = new char[len+1];
strcpy(desc,except_desc);
code = except_code;
}
CPdfException::CPdfException(CPdfException &s)
:desc(new char[strlen(s.desc)+1])
{
strcpy(desc,s.desc);
code = s.code;
}
CPdfException::~CPdfException()
{
if(desc)
delete desc;
};
void CPdfException::debug_print()
{
printf("Exception code %d at function %s./n",code,desc);
}