C++ 为什么';rethrown异常是否按预期工作?

C++ 为什么';rethrown异常是否按预期工作?,c++,exception,inheritance,C++,Exception,Inheritance,我的示例代码: #include<iostream> using namespace std; class Parent{ public: virtual void who() { cout<<"I am parent"<<endl; } }; class Child: public Parent { public:

我的示例代码:

#include<iostream>
using namespace std;

class Parent{ 
        public: 
            virtual void who()
            {
                cout<<"I am parent"<<endl;
            }
};
class Child: public Parent 
{
    public: 
        void who()
        {
            cout<<"I am child"<<endl;
        }
};

int main()
{
    try{
        try{
            Child C;
            Parent &P=C;
            throw P;
        }
        catch(Parent &P)
        {
            P.who();
            throw;//here it just propagates the Child exception
        }
    }
    catch(Parent &P)
    {
            P.who();//parent who is getting executed
    }

}
如果最初抛出的异常类型为
Special Widget
,则
catch
块将传播
Special Widget
异常,即使
w
的静态类型为Widget。这是因为当异常被重试时,不会生成副本

这不会抛出
特殊Widget
。它只抛出一个
小部件


抛出从不更改抛出对象的类型。如果原始对象是
子对象
,则抛出
后仍将是子对象

对于我来说,内部的catch已经打印出了
我是家长
(使用VC、clang和GCC)。因此,在
抛出之前或之后,异常绝不属于
Child
类型重新抛出是一种转移注意力的方法。因此,对象切片在这里发生了吗?“[except.throw]/3抛出异常副本会初始化(8.5,12.8)一个临时对象,称为异常对象。临时对象…用于初始化匹配处理程序(15.3)中声明的变量。”
不会抛出
rw
引用的对象,而是从
rw
初始化的临时对象副本。是的,这里有切片。
class Widget{...};
class Special Widget: public Widget { ... };
void passAndThrowWidget()
{
   SpecialWidget localSpecialWidget;
   ...
   Widget& rw = localSpecialWidget;
   throw rw; //this throws an exception of type Widget!
} 

................
................

catch(Widget &w)   //catch Widget exceptions
{
  ...
  throw;     //rethrow the exception so it continues to propagate.
}
.............
.............
throw rw; //this throws an exception of type Widget!