aboutsummaryrefslogtreecommitdiff
path: root/week10/Exercise01/Array.hpp
blob: 29a59065e117495370c13fdbdb8d7624bdc2e077 (plain) (blame)
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
#pragma once

template <class T>
class Array {
	T* arr;
	unsigned size;
	unsigned allocated;

	void resize();

	void free();
	void copyFrom(const Array& other);

public:
	Array();
	~Array();
	Array(const Array& other);
	Array& operator=(const Array& other);
	Array(Array&& other);
	Array& operator=(Array&& other);
};

template <class T>
void Array<T>::resize() {
	allocated *= 2;
	T* biggerArr = new T[allocated];
	for (int i = 0; i < size; i++) {
		biggerArr[i] = arr[i];
	}
	delete[] arr;
	arr = biggerArr;
}

template <class T>
void Array<T>::free() {
	delete[] arr;
}

template <class T>
void Array<T>::copyFrom(const Array& other) {
	this->size = other.size;
	this->allocated = other.allocated;
	this->arr = new T[allocated];
	for (int i = 0; i < size; i++) {
		this->arr[i] = other.arr[i];
	}
}

template <class T>
Array<T>::Array() {
	this->arr = nullptr;
	allocated = size = 0;
}

template <class T>
Array<T>::~Array() {
	free();
}

template <class T>
Array<T>::Array(const Array<T>& other) {
	copyFrom(other);
}

template <class T>
Array<T>& Array<T>::operator=(const Array<T>& other) {
	if (this != &other) {
		free();
		copyFrom(other);
	}
	return *this;
}

template <class T>
Array<T>::Array(Array<T>&& other) {
	this->arr = other.arr;
	other.arr = nullptr;
}

template <class T>
Array<T>& Array<T>::operator=(Array<T>&& other) {
	if (this != &other) {
		free();

		this->arr = other.arr;
		other.arr = nullptr;
	}
	return *this;
}