开发者

question about throwing an object

开发者 https://www.devze.com 2022-12-16 09:57 出处:网络
#include <iostream> using namespace std; class A{ public: A() {std::cout<<\"A() \";} A(const A& a){cout<<\"A(const 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{
         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

精彩评论

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

关注公众号