Re: Smart pointers and exceptions
On 2011-08-25 01:44, Iker Jamardo Zugaza wrote:
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:
class Foo
{
public: virtual ~Foo() {}
};
typedef tr1::shared_ptr<Foo> SPFoo;
class FooInherited: public Foo { };
typedef tr1::shared_ptr<FooInherited> SPFooInherited;
Let me alert you here, that even though FooInherited is derived from
Foo, there is no such inheritance relation betweeb SPFoo and SPFooInherited.
And let's check this test code:
int main(int argc, char** argv)
{
try
{
throw FooInherited();
}
catch(const Foo& f)
{
cout<< "Foo& caught!"<< endl;
}
This works, because FooInherited is a sub-class of Foo. The excpetion
object has type FooInherited and can thus enter a handler for type Foo.
try
{
throw SPFooInherited(new FooInherited());
}
catch(const SPFoo& f)
{
cout<< "SPFoo& caught!"<< endl;
}
return 0;
}
Everythign 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.
The incorrect assumption of this code is that an exception handler for
SPFoo could be entered with an exception object of type SPFooInherited.
This is not the case, because there does not exist any type-inheritance
relation between SPFooInherited and SPFoo. In fact, both SPFooInherited
and SPFoo are completely unrelated types.
HTH & Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]