Exception question

J

junw2000

class A
{
public:
A() { p_a = new int;}
~A() { delete p_a; } //Line1
private:
int *p_a;
}

void f()
{
try
{
A a1;
cout << "In f()" << endl;
g(); //Line2
A a2;
}
catch()
{
cout << "In catch" << endl;
}
}

void g()
{
cout << "In g()" << endl;
throw; //Line3
}

When an exception is thrown at Line3 in g(), stack will unwind at
Line2 in f(). When a1 is destructed, will Line1 be excecuted so that
p_a is deleted? How about a2?

Thanks.






}
 
S

Salt_Peter

class A
{
public:
A() { p_a = new int;}
~A() { delete p_a; } //Line1
private:
int *p_a;

}

void f()
{
try
{
A a1;
cout << "In f()" << endl;
g(); //Line2
A a2;
}
catch()
{
cout << "In catch" << endl;
}

}

void g()
{
cout << "In g()" << endl;
throw; //Line3

}

When an exception is thrown at Line3 in g(), stack will unwind at
Line2 in f(). When a1 is destructed, will Line1 be excecuted so that
p_a is deleted? How about a2?

Thanks.

}

When in doubt, prove it:

#include <iostream>

class A
{
int* p_a;
public:
A() : p_a(new int) { std::cout << "A()\n"; }
~A()
{
delete p_a;
std::cout << "~A()\n";
}
};

void g()
{
std::cout << "In g()" << std::endl;
throw 1; //Line3
}

void f()
{
try
{
A a1;
std::cout << "In f()" << std::endl;
g(); //Line2
A a2;
}
catch(...)
{
std::cout << "In catch" << std::endl;
}
}

int main()
{
f();
}

/*
A()
In f()
In g()
~A()
In catch
*/
 

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

Similar Threads

Tic Tac Toe Game 2
exception question 10
exception 2
Strange C++ compiling error 2
Exception caught inside a constructor 7
exception handling problem 3
Virtual function 2
Exception on Cygwin64/windows 8 1

Members online

No members online now.

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,211
Latest member
NelleWilde

Latest Threads

Top