我已经浏览过互联网,并且这个线程正在寻找一个完整的 回答我所面临的这种情况。我已经读过,扔智能指针 不是很聪明。我只是想明白为什么 是这样发生的。我将解释这种情况。让我们想象一下这个简单的 层次:智能指针和异常处理
class Foo
{
public: virtual ~Foo() {}
};
typedef tr1::shared_ptr<Foo> SPFoo;
class FooInherited: public Foo { };
typedef tr1::shared_ptr<FooInherited> SPFooInherited;
而且我们检查这个测试代码:
int main(int argc, char** argv)
{
try
{
throw FooInherited();
}
catch(const Foo& f)
{
cout << "Foo& caught!" << endl;
}
try
{
throw SPFooInherited(new FooInherited());
}
catch(const SPFoo& f)
{
cout << "SPFoo& caught!" << endl;
}
return 0;
}
一切编译,但在运行时 执行第二的try-catch不会。有人可以解释我为什么吗?特别是如果像 这样的代码行在运行时工作得很好。
void function(const SPFoo& f)
{
}
...
SPFooInherited fi(new FooInherited());
function(fi);
我明白,这个问题是SPFooInherited不会SPFoo(即使FooInherited从富继承)继承,但它深深地想知道什么是编译器/ RTE从函数调用示例做不同捕捉异常时不能解决问题。是否因为catch参数与函数调用参数不一样?为什么Foo &工作和SPFoo不?
非常感谢你提前。
Regards, Iker。