R. Clayton (rclayton@clayton.cs.monmouth.edu)
(no date)
I went a little over the top in my sermon against exceptions when I said that
exceptions going out of scope don't call destructors. If a class instance is
declared in the same scope in which an exception is thrown (perhaps indirectly)
then the instance's destructor is called, as the following code demonstrates:
$ cat t.cc
#include <iostream>
struct C {
const int i;
C(const int i) : i(i) { }
~C() { std::cerr << "In ~c(" << i << ").\n"; }
};
void f(void) {
C c(1);
char * cp = new char[10];
throw 1;
}
int main() {
try {
char * cp = new char[10];
C c(2);
f();
}
catch (int i) {
std::cerr << "Caught exception " << i << ".\n";
}
}
$ g++ -o t -ansi -pedantic -Wall t.cc
t.cc: In function `void f()':
t.cc:13: warning: unused variable `char*cp'
t.cc: In function `int main()':
t.cc:20: warning: unused variable `char*cp'
$ ./t
In ~c(1).
In ~c(2).
Caught exception 1.
$
However, the pointers assigned to the variables cp are unrecoverably lost.
This archive was generated by hypermail 2.0b3 on Fri May 10 2002 - 12:45:04 EDT