/
ConstructThrow.h
97 lines (79 loc) · 2.01 KB
/
ConstructThrow.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#pragma once
#include "stdafx.h"
#include "common.h"
/// Throws in constructor and demonstrates how the destructor is not called
/// and manually allocated resources are leaked.
/// Smart pointer (RAII), however, does get released.
class ConsThrow {
public:
ConsThrow(): m_smartptr('A') {
// allocate resource 1
m_resource1 = true;
// process something, throw exception
throw std::runtime_error("oops");
// allocate resource 2
m_resource2 = true;
}
~ConsThrow() {
// cleanup, never happens, resources are leaked
// m_smartptr is still cleaned though
m_resource1 = false;
m_resource2 = false;
ReportCleanup("ConsThrow");
}
private:
bool m_resource1;
bool m_resource2;
SmartResource m_smartptr;
};
/// A base class for further experiments.
class NoThrowBaseClass {
public:
NoThrowBaseClass() {
m_resource1 = 42; // magic number
}
~NoThrowBaseClass() {
m_resource1 = 0; // fake cleanup, is called because this class doesn't throw
ReportCleanup("NoThrowBaseClass");
}
protected:
int m_resource1;
};
class ConsThrowSubclass : public NoThrowBaseClass {
public:
ConsThrowSubclass() {
// allocate something
m_resource2 = 128;
// fail
throw std::runtime_error("oops");
}
~ConsThrowSubclass() {
// this destructor fails to run because of the exception
m_resource2 = 0;
ReportCleanup("ConsThrowSubclass");
}
protected:
int m_resource2;
};
/// Used for seeing behaviour of array allocation. The 3rd construction of this class throws
/// which means that array elements before it got constructed. They will be destructed immediately,
/// which is actually the only reasonable solution.
class LaterThrow {
public:
LaterThrow() {
std::cout << "Constructing LaterThrow: " << m_cnt << std::endl;
m_resource = m_cnt;
m_cnt += 1;
if (m_cnt == 3) {
std::cout << "Throwing..." << std::endl;
throw std::invalid_argument("just so");
}
}
~LaterThrow() {
ReportCleanup("LaterThrow", m_resource);
m_resource = 0;
}
int m_resource;
static int m_cnt;
};
int LaterThrow::m_cnt = 0;