Smart Pointers and Exception handling

Dear all,

I have looked over the internet and this thread looking for a complete
answer of this situation I am facing. I have read that throwing smart
pointers to objects is not very clever. I just want to understand why
is this happening. I will explain the situation. Let's imagine this
simple hierarchy:

1
2
3
4
5
6
7
8
9
10
class Foo 
{ 
public: virtual ~Foo() {} 
};

typedef tr1::shared_ptr<Foo> SPFoo; 

class FooInherited: public Foo { }; 

typedef tr1::shared_ptr<FooInherited> SPFooInherited; 

And let's check this test code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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; 
} 


Everything compiles but in runtime the second try-catch won't be
executed. Can someone explain me why? Specially if lines of code like
this work perfectly fine in runtime.

1
2
3
4
5
6
7
8
void function(const SPFoo& f) 
{ 
} 

... 

SPFooInherited fi(new FooInherited()); 
function(fi); 

Thank you very much in advance.
Regards,
Iker.
No matter what the relation between template arguments is, the templates themselves are not related. I can't say why a const reference argument works though..
Topic archived. No new replies allowed.