构造函数中的异常

C++语言: Codee#25752
01 #include <iostream>
02
03 using namespace std;
04
05 class Trace
06 {
07     static int counter;
08     int objid;
09 public:
10     Trace()
11     {
12         objid = ++counter;
13         cout << "constructing Trace #" << objid << endl;
14         if(objid == 3)
15             throw 3;
16     }
17     ~Trace()
18     {
19         cout << "destructing Trace #" << objid << endl;
20     }
21 };
22
23 int Trace::counter = 0;
24
25 int main()
26 {
27     try
28     {
29         Trace n1;
30         Trace array[5];
31         Trace n2;
32     }
33     catch(int i)
34     {
35         cout << "caught " << i << endl;
36     }
37
38     return 0;
39 }
40 /*
41 constructing Trace #1
42 constructing Trace #2
43 constructing Trace #3           //throw exception before this object was completely constructed!
44 destructing Trace #2
45 destructing Trace #1
46 caught 3
47
48 Process returned 0 (0x0)   execution time : 0.092 s
49 Press any key to continue.
50
51
52
53 */

C++语言: Codee#25753
01 /*
02     已经成功构造的cat对象不会被销毁
03     导致内存泄漏
04     */
05
06 #include <iostream>
07 #include <cstddef>
08 using namespace std;
09
10 class Cat
11 {
12 public:
13     Cat()
14     {
15         cout << "Cat()" << endl;
16     }
17     ~Cat()
18     {
19         cout << "~Cat()" << endl;
20     }
21 };
22
23 class Dog
24 {
25 public:
26     void* operator new(size_t sz)
27     {
28         cout << "allocating a Dog" << endl;
29         throw 47;
30     }
31     void operator delete(void* p)
32     {
33         cout << "deallocating a Dog" << endl;
34         ::operator delete(p);
35     }
36 };
37
38 class UseResources
39 {
40     Cat* bp;
41     Dog* op;
42 public:
43     UseResources(int count = 1)
44     {
45         cout << "UseResources()" << endl;
46         bp = new Cat[count];
47         op = new Dog;
48     }
49     ~UseResources()
50     {
51         cout << "~UseResources()" << endl;
52         delete []bp;
53         delete op;
54     }
55 };
56
57 int main()
58 {
59     try
60     {
61         UseResources ur(3);
62     }
63     catch(int)
64     {
65         cout << "inside handler" << endl;
66     }
67
68     return 0;
69 }
70 /*
71 UseResources()
72 Cat()
73 Cat()
74 Cat()
75 allocating a Dog
76 inside handler
77
78 Process returned 0 (0x0)   execution time : 0.065 s
79 Press any key to continue.
80
81
82
83
84
85
86 */
原文地址:https://www.cnblogs.com/invisible/p/2387228.html