我已經瀏覽過互聯網,並且這個線程正在尋找一個完整的 回答我所面臨的這種情況。我已經讀過,扔智能指針 不是很聰明。我只是想明白爲什麼 是這樣發生的。我將解釋這種情況。讓我們想象一下這個簡單的 層次:智能指針和異常處理
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。