开发者

question about throwing an object

#include <iostream>
using namespace std;

class A{
public:
    A() {std::cout<<"A() ";}
    A(const A& a){cout<<"A(const A&) ";}
    ~A(){cout<<"~A() ";}

    virtual void Foo(){cout<<"A::Foo() ";}
};

class B: public A
{
public:
    B(){std::cout<<"B() ";}
    B(const B& a){cout<<"B(const B&) ";}
    ~B(){cout<<"~B() ";}

    virtual void Foo() {cout<<"B::Foo() ";}

};

int main()
{
    try{
         B b;
         throw b;                        //throw like this
    }
    catch(A ex){
        ex.Foo();
    }
    catch(B ex){
        ex.Foo();
    }
    catch(A * ex){
        ex->Foo();
    }
    catch(B * ex){
        ex->Foo();
    }

    return 0;
}

The output is

A() B() A() B(const B&) ~B() ~A() A(const A&) A::Foo() ~A() ~B() ~A()

#include <iostream>
using namespace std;

class A{
public:
    A() {std::cout<<"A() ";}
    A(const A& a){cout<<"A(const A&) ";}
    ~A(){cout<<"~A() ";}

    virtual void Foo(){cout<<"A::Foo() ";}
};

class B: public A
{
public:
    B(){std::cout<<"B() ";}
    B(const B& a){cout<<"B(const B&) ";}
    ~B(){cout<<"~B() ";}

    virtual void Foo() {cout<<"B::Foo() ";}

};

int main()
{
    try{

         throw B();              //throw it this way
    }
    catch(A ex)开发者_如何学Python{
        ex.Foo();
    }
    catch(B ex){
        ex.Foo();
    }
    catch(A * ex){
        ex->Foo();
    }
    catch(B * ex){
        ex->Foo();
    }

    return 0;
}

The output is

A() B() A(const A&) A::Foo() ~A() ~B() ~A()

Can anybody explain the difference to me? The difference is

A() B(const B&) ~B() ~A()

Why is the copy constructor of class B invoked?

Thanks so much!


Because in the first sample the local variable b is first being copied at the throw line, and then sliced at the catch ( A ex ) line, while in the second sample only the second copy is performed.

I think I have to mention the throw by value, catch by reference mantra here :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜