class X {
public:
class XExc {
public:
XExc() { cout << "Constructor X::XExc" << endl; }
// XExc(const XExc&) { cout << "Copy X::XExc" << endl; }
~XExc() { cout << "Destuctor X::XExc" << endl; }
};
void f() {
cout << "Inside f" << endl;
throw XExc(); }
};
int main() {
X x;
try {
x.f();
} catch(X::XExc&) {
cout << "Exception handler" << endl;
}
}
Exceptions : Something I'm missing ?[SOLVED]
Hi.
I am now studying exceptions in C++. I wrote code to test destruction of thrown exception objects and when they occur. The output is somewhat strange.
Here is the code:
The output is :
Inside f
Constructor X::XExc
Destuctor X::XExc
Exception handler
Destuctor X::XExc
So the first destructor destroys the original XExc and the second destroys the copy made when throw is encountered.(at least that's how i see it)
But, notice I commented the copy-constructor. If I explicitly specify one, there's no Destructor before the handler, but there's no copy constructor output either. I am a little confused here.
[Edited by - Mocanu Razvan on April 14, 2006 4:29:41 AM]
Someone please correct me if I am wrong but I am not sure you should be catching a reference like that.
Quote:Original post by EasilyConfused
Someone please correct me if I am wrong but I am not sure you should be catching a reference like that.
Why not? Though you should probably catch it as const reference...
To the OP: It seems like it's able to optimize away the temporary when the copy constructor is user-defined. Not sure exactly why it won't optimize it when it's compiler-generated...
Throw by value, catch by reference.
I come to the same conclusion as RDragon. You might try making your example a little less contrived (throw from a deeper point, so more unwinding occurs, give your class some actual data to copy, et cetera) and see how things change.
I come to the same conclusion as RDragon. You might try making your example a little less contrived (throw from a deeper point, so more unwinding occurs, give your class some actual data to copy, et cetera) and see how things change.
Quote:Original post by RDragon1
To the OP: It seems like it's able to optimize away the temporary when the copy constructor is user-defined. Not sure exactly why it won't optimize it when it's compiler-generated...
Perhaps it's because he is compiling without optimizations? When run in "Release" mode in VC++2005, it behaves "correctly".
jfl.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement