-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathA18-5-2.cpp
More file actions
115 lines (82 loc) · 1.97 KB
/
A18-5-2.cpp
File metadata and controls
115 lines (82 loc) · 1.97 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
// Rule: A18-5-2
// Source line: 29476
// Original file: A18-5-2.cpp
// $Id: A18-5-2.cpp 289436 2017-10-04 10:45:23Z michal.szczepankiewicz $
#include <cstdint>
#include <memory>
#include <vector>
std::int32_t Fn1()
{
std::int32_t errorCode{0};
std::int32_t* ptr =
new std::int32_t{0}; // Non-compliant - new called explicitly
// ...
if (errorCode != 0)
{
throw std::runtime_error{"Error"}; // Memory leak could occur here
}
// ...
if (errorCode != 0)
{
return 1; // Memory leak could occur here
}
// ...
return errorCode; // Memory leak could occur here
}
std::int32_t Fn2()
{
std::int32_t errorCode{0};
std::unique_ptr<std::int32_t> ptr1 = std::make_unique<std::int32_t>(
0); // Compliant - alternative for ’new std::int32_t(0)’
std::unique_ptr<std::int32_t> ptr2(new std::int32_t{
0}); // Non-compliant - unique_ptr provides make_unique
// function which shall be used instead of explicit
// new operator
std::shared_ptr<std::int32_t> ptr3 =
std::make_shared<std::int32_t>(0);
// Compliant
std::vector<std::int32_t> array;
// Compliant
// alternative for dynamic array
if (errorCode != 0)
{
throw std::runtime_error{"Error"};
}
// ...
if (errorCode != 0)
{
return 1; // No memory leaks
}
// ...
return errorCode; // No memory leaks
// No memory leaks
}
template<typename T>
class ObjectManager
{
public:
explicit ObjectManager(T* obj) : object{obj} {}
~ObjectManager() {
delete object;
}
// Implementation
private:
T* object;
};
std::int32_t Fn3()
{
std::int32_t errorCode{0};
ObjectManager<std::int32_t> manager{
new std::int32_t{0}}; // Compliant by exception
if (errorCode != 0)
{
throw std::runtime_error{"Error"}; // No memory leak
}
// ...
if (errorCode != 0)
{
return 1; // No memory leak
}
// ...
return errorCode; // No memory leak
}