-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcert-CTR56.cpp
95 lines (74 loc) · 1.56 KB
/
cert-CTR56.cpp
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
//
// CTR56-CPP. Do not use pointer arithmetic on polymorphic objects
//
#include <array>
#include <iostream>
namespace {
constexpr size_t SIZE = 5;
size_t globI{};
double globD{};
struct S
{
int i;
S() : i(globI++) {}
};
struct T : S
{
double d;
T() : d(globD++) {}
};
void foo(const S* someSes, std::size_t count)
{
for (const S* end = someSes + count; someSes != end; ++someSes) { // undefined behavior
std::cout << someSes->i << ", ";
}
std::cout << std::endl;
}
void bar(const S* someSes, std::size_t count)
{
for (std::size_t i = 0; i < count; ++i) { // undefined behavior
std::cout << someSes[i].i << ", ";
}
std::cout << std::endl;
}
void bad()
{
T test[SIZE];
foo(test, SIZE);
bar(test, SIZE);
}
void fun(const S* const* someSes, std::size_t count)
{
for (const S* const* end = someSes + count; someSes != end; ++someSes) {
std::cout << (*someSes)->i << ", ";
}
std::cout << std::endl;
}
// ========================
void notGood()
{
S* test[SIZE] = {new T, new T, new T, new T, new T};
fun(test, SIZE);
for (auto* v : test) {
delete v;
}
bad();
}
template <typename Iter> void better(Iter i, Iter e)
{
for (; i != e; ++i) {
std::cout << (*i)->i << ", ";
}
std::cout << std::endl;
}
} // namespace
int main()
{
std::array<S*, SIZE> test{new T, new T, new T, new T, new T};
better(test.cbegin(), test.cend());
for (auto* v : test) {
delete v;
}
notGood();
return static_cast<int>(globI < (4 * SIZE));
}