-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInitializerList.cpp
80 lines (63 loc) · 1.72 KB
/
InitializerList.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
/**
* \file InitializerList.cpp
* \brief lightweight proxy object that provides access to an array of objects of type const T
*
* \see https://www.learncpp.com/cpp-tutorial/stdinitializer_list/
*/
#include <StdStream/StdStream.h>
#include <StdTest/StdTest.h>
#include <Stl.h>
//--------------------------------------------------------------------------------------------------
class ArrayInt
{
public:
ArrayInt() = default;
ArrayInt(const ArrayInt &) = delete; // to avoid shallow copies
ArrayInt &operator = (const ArrayInt &) = delete; // to avoid shallow copies
explicit ArrayInt(const std::size_t a_size) :
_size {a_size},
_data { new int[a_size] {} }
{
}
// allow ArrayInt to be initialized via list initialization (pass by value)
explicit ArrayInt(std::initializer_list<int> a_list) :
ArrayInt( a_list.size() )
{
// Now initialize our array from the list
std::size_t count {};
for (const auto it_item : a_list) {
_data[count] = it_item;
++ count;
}
}
~ArrayInt()
{
delete[] _data; _data = nullptr;
}
const int & operator [] (const std::size_t a_index) const
{
STD_TEST(a_index < _size);
return _data[a_index];
}
std::size_t size() const
{
return _size;
}
private:
const std::size_t _size {};
int *_data {};
};
//--------------------------------------------------------------------------------------------------
int main(int, char **)
{
const ArrayInt array {1, 3, 5, 7, 9, 11};
for (std::size_t count {}; count < array.size(); ++ count) {
std::cout << array[count] << ' ';
}
std::cout << std::endl;
return EXIT_SUCCESS;
}
//--------------------------------------------------------------------------------------------------
#if OUTPUT
1 3 5 7 9 11
#endif