-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathA18-1-6.cpp
More file actions
123 lines (84 loc) · 1.98 KB
/
A18-1-6.cpp
File metadata and controls
123 lines (84 loc) · 1.98 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
// Rule: A18-1-6
// Source line: 28960
// Original file: A18-1-6.cpp
// $Id: A18-1-6.cpp 311792 2018-03-15 04:15:08Z christof.meerwald $
#include <cstdint>
#include <functional>
#include <string>
#include <unordered_map>
class A
{
public:
A(uint32_t x, uint32_t y) noexcept : x(x), y(y) {}
uint32_t GetX() const noexcept {
return x;
}
uint32_t GetY() const noexcept {
return y;
}
friend bool operator == (const A &lhs, const A &rhs) noexcept
{
return lhs.x == rhs.x && lhs.y == rhs.y;
}
private:
uint32_t x;
uint32_t y;
};
class B
{
public:
B(uint32_t x, uint32_t y) noexcept : x(x), y(y) {}
uint32_t GetX() const noexcept {
return x;
}
uint32_t GetY() const noexcept {
return y;
}
friend bool operator == (const B &lhs, const B &rhs) noexcept
{
return lhs.x == rhs.x && lhs.y == rhs.y;
}
private:
uint32_t x;
uint32_t y;
};
namespace std
{
// Compliant
template<>
struct hash<A>
{
std::size_t operator()(const A& a) const noexcept
{
auto h1 = std::hash<decltype(a.GetX())>{}(a.GetX());
std::size_t seed { h1 + 0x9e3779b9 };
auto h2 = std::hash<decltype(a.GetY())>{}(a.GetY());
seed ^= h2 + 0x9e3779b9 + (seed << 6) + (seed >> 2);
return seed;
}
};
// Non-compliant: string concatenation can potentially throw
template<>
struct hash<B>
{
std::size_t operator()(const B& b) const
{
std::string s{std::to_string(b.GetX()) + ’,’ + std::to_string(b.GetY())};
return std::hash<std::string>{}(s);
}
};
}
int main()
{
std::unordered_map<A, bool> m1 { { A{5, 7}, true } };
if (m1.count(A{4, 3}) != 0)
{
// ....
}
std::unordered_map<B, bool> m2 { { B{5, 7}, true } };
// Lookup can potentially throw if hash function throws
if (m2.count(B{4, 3}) != 0)
{
// ....
}
}