Construction and destruction of objects when exceptions are thrown

T

thamizh.veriyan

I compiled this code on gcc 4.1.2 and the output I got seems to be a
bit weird.

Here is the code:

#include <iostream>

class A{
public:
A(){std::cout << "Constructor" << std::endl;}
~A(){std::cout << "Destructor" << std::endl;}
};

void display(){
A mystr;
throw mystr;
}

int main() {
try{
display();
}
catch(A str){
}
return 0;
}

The output happens to be:
Constructor
Destructor
Destructor
Destructor

I don't know if I am missing something. I checked all the references
that I have for exceptions. Looks like local objects get deleted
normally when exceptions are thrown. I cant seem to explain this
output. Would be grateful if the members here can help me with this.

Regards
Dana
 
V

Victor Bazarov

I compiled this code on gcc 4.1.2 and the output I got seems to be a
bit weird.

Here is the code:

#include <iostream>

class A{
public:
A(){std::cout << "Constructor" << std::endl;}
~A(){std::cout << "Destructor" << std::endl;}
};

void display(){
A mystr;
throw mystr;
}

int main() {
try{
display();
}
catch(A str){
}
return 0;
}

The output happens to be:
Constructor
Destructor
Destructor
Destructor

I don't know if I am missing something. I checked all the references
that I have for exceptions. Looks like local objects get deleted
normally when exceptions are thrown. I cant seem to explain this
output. Would be grateful if the members here can help me with this.

Your 'A' class has a copy constructor which you forgot to consider.

V
 
V

Victor Bazarov

John said:
It's just incredible how many times we get this post.

If it's so frequently asked (which I can't vouch for), then perhaps
somebody <wink-wink> could write up an entry for Marshall Cline to
add to the FAQ Lite...

V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top