-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathA15-2-2.cpp
More file actions
149 lines (113 loc) · 2.61 KB
/
A15-2-2.cpp
File metadata and controls
149 lines (113 loc) · 2.61 KB
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
// Rule: A15-2-2
// Source line: 24446
// Original file: A15-2-2.cpp
//% $Id: A15-2-2.cpp 289436 2017-10-04 10:45:23Z michal.szczepankiewicz $
#include <fstream>
#include <stdexcept>
class A
{
public:
A() = default;
};
class C1
{
public:
C1()
noexcept(false)
: a1(new A), a2(new A) // Non-compliant - if a2 memory allocation
// fails, a1 will never be deallocated
{}
C1(A* pA1, A* pA2)
noexcept : a1(pA1), a2(pA2) // Compliant - memory allocated outside of C1
// constructor, and no exceptions can be thrown
{}
private:
A* a1;
A* a2;
};
class C2
{
public:
C2() noexcept(false) : a1(nullptr), a2(nullptr)
{
try
{
a1 = new A;
a2 = new A; // If memory allocation for a2 fails, catch-block will
// deallocate a1
}
catch (std::exception& e)
{
throw; // Non-compliant - whenever a2 allocation throws an
// exception, a1 will never be deallocated
}
}
private:
A* a1;
A* a2;
};
class C3
{
public:
C3() noexcept(false) : a1(nullptr), a2(nullptr), file("./filename.txt")
{
try
{
a1 = new A;
a2 = new A;
if (!file.good())
{
throw std::runtime_error("Could not open file.");
}
}
catch (std::exception& e)
{
delete a1;
a1 = nullptr;
delete a2;
a2 = nullptr;
file.close();
throw; // Compliant - all resources are deallocated before the
// constructor exits with an exception
}
}
private:
A* a1;
A* a2;
std::ofstream file;
};
class C4
{
public:
C4() : x(0), y(0)
{
// Does not need to check preconditions here - x and y initialized with
// correct values
}
C4(std::int32_t first, std::int32_t second)
noexcept(false) : x(first), y(second)
{
CheckPreconditions(x,
y); // Compliant - if constructor failed to create a
// valid object, then throw an exception
}
static void CheckPreconditions(std::int32_t x,
std::int32_t y) noexcept(false)
{
if (x < 0 || x > 1000)
{
throw std::invalid_argument(
"Preconditions of class C4 were not met");
}
else if (y < 0 || y > 1000)
{
throw std::invalid_argument(
"Preconditions of class C4 were not met");
}
}
private:
std::int32_t x;
std::int32_t y;
// Acceptable range: <0; 1000>
// Acceptable range: <0; 1000>
};