Re: How expensive are exceptions?
On Wed, 6 Jun 2007, Risto Lankinen wrote:
Observe this program to print "Base" (the compile-time
type of the thrown object) whereas if RTTI were used it
would print "Derived" (the run-time type of the thrown
object):
- - -
int main()
{
Base *p = new Derived;
try
{
throw *p;
}
catch( const Derived & )
{
cout << "Derived" << endl;
}
catch( const Base & )
{
cout << "Base" << endl;
}
catch( ... )
{
cout << "<unknown>" << endl;
}
delete p;
return 0;
}
Catching and throwing are different things. Catching is done based on the
run-time type. Throwing is done based on compile-time type. In particular,
if you modify your program as such:
catch( const Base &e )
{
cout << typeid(e).name() << endl;
}
the printed name will identify Base, not Derived. The thrown object has a
dynamic type of Base.
The reason is simple: it is a *copy* of the throw-expression that is
thrown, not the throw-expression itself. Not the object you allocated on
the heap is thrown, but a copy of it. Go ahead, give your object a copy
constructor. It will be called. Specifically, Base's copy constructor is
called, because that's how copying works. It's just like calling a
function with a by-value argument of type Base and passing *p.
Oh, by the way, you're also slicing the object.
Sebastian Redl
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]