Topic: Exception gurus - Copy constructors of exc


Author: clamage@Eng.Sun.COM (Steve Clamage)
Date: 1998/02/05
Raw View
In article k23@netlab.cs.rpi.edu, Nicholas howden <howden@lineone.net> writes:
>
>When is an exception's copy constructor called?

Whenever a copy is needed. More below.

>Stroustrup's C++ book says that "In principle, an exception is copied
>when it is thrown, so the handler gets hold of a copy of the original
>exception.". Does this apply when the exception is caught by reference?

Yes. The "throw" always throws a copy, and the copy constructor is
used to make the copy.

>Is it always necessary to copy exceptions because the stack is being
>unwound and the originial objects are destroyed?

That is basically the reason.

>Stroustrup also says that if an exception is caught by value as a Base
>class, then the handler does not have access to the attributes of the
>derived class. Is this simply because you cannot (legally) cast it
>upwards,
>or is the object actually copied as its base class in this situation?
>
>When the call stack is unwound, is the exception copied at every level of
>indirection whether there is a handler or not at that level, or is it
>only copied where there is something to catch it? Is this implementation
>specific or a definition in ANSI C++?

The language rules say that a temporary copy is made at the point of
the throw; the stack is unwound until a handler is reached, at which
point the object is used to initialize the catch-clause parameter. This
is essenitally the same thing that happens when you pass an argument to
a function.

If you pass a derived object by value to a base class target (function
or catch clause parameter), only the base part is copied. The target
cannot hold a derived object, so there is no choice in the matter.
Polymorphism applies only to pointers and references. The object received
by value is no longer a derived object, but has been "sliced" down to a
base object.

As always, the "as-if" principle may allow the compiler to take
some shortcuts.

For the gory details, see draft standard section 15.1 "Throwing an exception".

---
Steve Clamage, stephen.clamage@sun.com
---
[ comp.std.c++ is moderated.  To submit articles: try just posting with      ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu         ]
[ FAQ:      http://reality.sgi.com/employees/austern_mti/std-c++/faq.html    ]
[ Policy:   http://reality.sgi.com/employees/austern_mti/std-c++/policy.html ]
[ Comments? mailto:std-c++-request@ncar.ucar.edu                             ]