小编Ike*_*rdo的帖子

智能指针和异常处理

我已经浏览了互联网,这个主题正在寻找我面临的这种情况的完整答案.我已经读过,向对象投掷智能指针并不是很聪明.我只是想明白为什么会这样.我会解释一下情况.让我们想象一下这个简单的层次结构

class Foo 
{ 
public: virtual ~Foo() {} 
}; 

typedef tr1::shared_ptr<Foo> SPFoo; 

class FooInherited: public Foo { }; 

typedef tr1::shared_ptr<FooInherited> SPFooInherited; 
Run Code Online (Sandbox Code Playgroud)

让我们检查一下这个测试代码:

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; 
} 
Run Code Online (Sandbox Code Playgroud)

一切都编译但在运行时第二次try-catch不会被执行.有人能解释一下为什么吗?特别是如果这样的代码行在运行时完全正常.

void function(const SPFoo& f) 
{ 
} 

... 

SPFooInherited fi(new FooInherited()); 
function(fi);
Run Code Online (Sandbox Code Playgroud)

我确实理解问题是SPFooInherited不从SPFoo继承(即使FooInherited继承自Foo),但它非常想知道什么是编译器/ RTE与函数调用示例的不同之处在于捕获异常不是能够解决de情况.是因为catch参数与函数调用参数不同吗?为什么Foo&works和SPFoo没有?

非常感谢你提前.

此致,伊克尔.

c++ exception smart-pointers

8
推荐指数
1
解决办法
1581
查看次数

标签 统计

c++ ×1

exception ×1

smart-pointers ×1