异常变量生命周期
测试1(返回对象会多拷贝一份浪费内存)
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
class MyException
{
public:
MyException()
{
cout << "MyException的默认构造" << endl;
}
MyException(const MyException & e)
{
cout << "MyException的拷贝构造" << endl;
}
~MyException()
{
cout << "MyException的析构调用" << endl;
}
};
void doWork()
{
throw MyException();
}
void test01()
{
try
{
doWork();
}
catch (MyException e)//普通写法会多开销一份数据
{
cout << "捕获异常" << endl;
}
}
int main(){
test01();
system("pause");
return EXIT_SUCCESS;
}
运行
MyException的默认构造
MyException的拷贝构造
捕获异常
MyException的析构调用
MyException的析构调用
测试2(推荐返回引用)
把catch (MyException e)
改为catch (MyException &e)
,改成返回引用。
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
class MyException
{
public:
MyException()
{
cout << "MyException的默认构造" << endl;
}
MyException(const MyException & e)
{
cout << "MyException的拷贝构造" << endl;
}
~MyException()
{
cout << "MyException的析构调用" << endl;
}
};
void doWork()
{
throw MyException();
}
void test01()
{
try
{
doWork();
}
catch (MyException &e)
{
cout << "捕获异常" << endl;
}
}
int main(){
test01();
system("pause");
return EXIT_SUCCESS;
}
运行
MyException的默认构造
捕获异常
MyException的析构调用
测试3(返回指针不推荐)
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
class MyException
{
public:
MyException()
{
cout << "MyException的默认构造" << endl;
}
MyException(const MyException & e)
{
cout << "MyException的拷贝构造" << endl;
}
~MyException()
{
cout << "MyException的析构调用" << endl;
}
};
void doWork()
{
throw &MyException();
}
void test01()
{
try
{
doWork();
}
catch (MyException *e)
{
cout << "捕获异常" << endl;
delete e;//靠自觉 释放对象
}
}
int main(){
test01();
return 0;
}