File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ #include < string>
2+ #include < iostream>
3+ #include < typeinfo>
4+ #include < tr1/memory>
5+
6+ using namespace std ;
7+
8+ class MyException {};
9+ class Dummy
10+ {
11+ public:
12+ Dummy (string s) : MyName(s) { PrintMsg (" Created Dummy:" ); }
13+ Dummy (const Dummy& other) : MyName(other.MyName){ PrintMsg (" Copy created Dummy:" ); }
14+ ~Dummy (){ PrintMsg (" Destroyed Dummy:" ); }
15+ void PrintMsg (string s) { cout << s << MyName << endl; }
16+ string MyName;
17+ int level;
18+ };
19+
20+
21+ void C (Dummy d, int i)
22+ {
23+ cout << " Entering FunctionC" << endl;
24+ d.MyName = " C" ;
25+ throw MyException ();
26+
27+ cout << " Exiting FunctionC" << endl;
28+ }
29+
30+ void B (Dummy d, int i)
31+ {
32+ cout << " Entering FunctionB" << endl;
33+ d.MyName = " B" ;
34+ C (d, i + 1 );
35+ cout << " Exiting FunctionB" << endl;
36+ }
37+
38+ void A (Dummy d, int i)
39+ {
40+ cout << " Entering FunctionA" << endl;
41+ d.MyName = " A" ;
42+ // Dummy* pd = new Dummy("new Dummy"); //Not exception safe!!!
43+ tr1::shared_ptr<Dummy> sp (new Dummy (" new Dummy" ));
44+ B (d, i + 1 );
45+ // delete pd;
46+ cout << " Exiting FunctionA" << endl;
47+ }
48+
49+
50+ int main ()
51+ {
52+ cout << " Entering main" << endl;
53+ try
54+ {
55+ Dummy d (" M" );
56+ A (d,1 );
57+ }
58+ catch (MyException& e)
59+ {
60+ cout << " Caught an exception of type: " << typeid (e).name () << endl;
61+ }
62+
63+ cout << " Exiting main." << endl;
64+ char c;
65+ cin >> c;
66+ }
67+
68+ /* Output:
69+ Entering main
70+ Created Dummy: M
71+ Copy created Dummy: M
72+ Entering FunctionA
73+ Copy created Dummy: A
74+ Entering FunctionB
75+ Copy created Dummy: B
76+ Entering FunctionC
77+ Destroyed Dummy: C
78+ Destroyed Dummy: B
79+ Destroyed Dummy: A
80+ Destroyed Dummy: M
81+ Caught an exception of type: class MyException
82+ Exiting main.
83+
84+ */
You can’t perform that action at this time.
0 commit comments