C++异常问题

[复制链接]
1346|5
 楼主| gxgclg 发表于 2013-6-28 23:20 | 显示全部楼层 |阅读模式
class TestClass
{
public:
    TestClass()
    {
        cout << "Construtor TestClass" << endl;
    }
     
    ~TestClass()
    {
        cout << "Destructor TestClass" << endl;
    }
};

class Exception1
{
public:
    Exception1()
    {
        cout << "Construtor Exception1" << endl;
    }

    ~Exception1()
    {
        cout << "Destructor Exception1" << endl;
    }
};

int test()
{
    TestClass t;

    throw Exception1();
}

int _tmain(int argc, _TCHAR* argv[])
{
    try
    {
        test();
    }
    catch (...)
    {

    }
     
    return 0;
}
这个的执行结果为:
Construtor TestClass
Construtor Exception1
Destructor Exception1
Destructor TestClass
Destructor Exception1

为什么“Destructor Exception1”会执行两次啊??
无冕之王 发表于 2013-6-28 23:32 | 显示全部楼层
为 Exception1 定义一个拷贝构造函数再去观察下结果.
yybj 发表于 2013-6-28 23:52 | 显示全部楼层
或许是局部函数里构造了一个,退出函数的时候析构一个,还返回了一个
秋天落叶 发表于 2013-6-28 23:54 | 显示全部楼层
throw语句抛出的是一个函数对象时,改为类对象
sinadz 发表于 2013-6-29 12:44 | 显示全部楼层
无冕之王 发表于 2013-6-28 23:32
为 Exception1 定义一个拷贝构造函数再去观察下结果.

LZ可以试试看
baidudz 发表于 2013-6-29 12:49 | 显示全部楼层
yybj 发表于 2013-6-28 23:52
或许是局部函数里构造了一个,退出函数的时候析构一个,还返回了一个

应该就是这个原因
您需要登录后才可以回帖 登录 | 注册

本版积分规则

177

主题

1653

帖子

1

粉丝
快速回复 在线客服 返回列表 返回顶部