C++边边角角(二)

 #include <stdio.h>

struct Ex
{
    static int gId;
    int id;
    Ex(){id=gId++;printf("Ex()-id=%d/n",id);}
    Ex(const Ex &e){id=gId++;printf("Ex(e)-id=%d,copy from %d/n", id, e.id);}
    ~Ex(){printf("~Ex()-id=%d/n",id);}
};
int Ex::gId;

void func1(void)
{
    try
    {
        throw Ex(); // create
    }
    catch (Ex e)    // copy
    {
    }   //all destructed
}
void func2(void)
{
    try
    {
        throw Ex(); // create
    }
    catch (Ex &e)
    {
    }   //all destructed
}
void func3(void)
{
    try
    {
        Ex e;       // create
        throw e;    // copy, why it needs to be copied, see func6
    }
    catch (Ex e)    // copy
    {
    }   //all destructed
}
void func4(void)
{
    try
    {
        Ex e;       // create
        throw e;    // copy
    }
    catch (Ex &e)
    {
    }   //all destructed
}
void func5(void)
{
   
Ex e;       // create (1)

    try
    {
        throw e;    // copy (2)
    }
    catch (Ex &e)
    {
        printf("leaving5-exh/n");
    }   //(2)destructed
    printf("leaving5/n");   // (1) destructed
}
void func6(void)
{
    Ex e;       // create (1)
    try
    {
        throw e;    // copy (2), this one is copied so that it can be delivered to the caller
                    // i guess there is some mem area as oppposed to the calling stack used
                    // to hold the exception object. So once throwing is invoked, an exception object
                    // is always created either by ordinary constructor or copy constructor
.
    }
    catch(int)
    {
    }
    //(1) destructed
}


int main(void)
{
    printf("========func1========/n");
    func1();
    printf("========func2========/n");
    func2();
    printf("========func3========/n");
    func3();
    printf("========func4========/n");
    func4();
    printf("========func5========/n");
    func5();
    printf("========func6========/n");
    try{
        func6();
    }
    catch(...)
    {
        printf("dealing with ex from func6/n");
    } //(2) destructed   
    printf("finished/n");
    return 0;
}

posted @ 2008-09-05 01:54  quanben  阅读(148)  评论(0编辑  收藏  举报