打印

C++异常问题

[复制链接]
904|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语句抛出的是一个函数对象时,改为类对象

使用特权

评论回复
5
sinadz| | 2013-6-29 12:44 | 只看该作者
无冕之王 发表于 2013-6-28 23:32
为 Exception1 定义一个拷贝构造函数再去观察下结果.

LZ可以试试看

使用特权

评论回复
6
baidudz| | 2013-6-29 12:49 | 只看该作者
yybj 发表于 2013-6-28 23:52
或许是局部函数里构造了一个,退出函数的时候析构一个,还返回了一个

应该就是这个原因

使用特权

评论回复
发新帖 我要提问
您需要登录后才可以回帖 登录 | 注册

本版积分规则

177

主题

1653

帖子

1

粉丝