As a C++ beginner coming from Java, I have become increasingly confused on the topic of memory management and how to avoid memory leaks. Is the code below risking a memory leak that I'm not currently aware of? Any help or constructive feedback would be greatly appreciated.
#pragma once
template <class T>
class DynamicArray {
private:
T *m_arr;
int m_length; //amount of elements currently being stored in the array
int m_capacity; //actual size of the array
public:
DynamicArray();
~DynamicArray();
T get(int index); //O(1)
void add(T obj); //no need to push any objects forward, O(1)
void insert(int index, T obj); //pushes forward all objects in front of the given index, then sets the obj at the given index, O(n)
void set(int index, T obj); //sets the given index of m_arr as obj, O(1)
void remove(int index); //removes the object at the given index and pushes all the array contents back, O(n)
int size(); //O(1)
void print();
};
#include <iostream>
#include "Header.h"
template<class T>
DynamicArray<T>::DynamicArray() : m_arr(new T[1]), m_length(0), m_capacity(1) {}
template<class T>
DynamicArray<T>::~DynamicArray() {
delete[] m_arr;
}
template<class T>
T DynamicArray<T>::get(int index) {
if (index < m_length && index >= 0)
return m_arr[index];
else throw ("Index out of bounds!");
}
template<class T>
void DynamicArray<T>::set(int index, T obj) {
if (index < m_length && index >= 0) {
m_arr[index] = obj;
} else throw ("Index out of bounds!");
}
template<class T>
void DynamicArray<T>::add(T obj) {
if (m_length == m_capacity) {
T *new_arr = new T[m_length * 2];
for (int i = 0; i < m_length; i++) {
new_arr[i] = m_arr[i];
}
delete[] m_arr;
m_arr = new_arr;
m_capacity = m_capacity * 2;
}
m_arr[m_length] = obj;
m_length++;
}
template<class T>
void DynamicArray<T>::insert(int index, T obj) {
if (index < m_length && index >= 0) {
int size;
if (m_length == m_capacity) size = m_length * 2;
else size = m_capacity;
T *new_arr = new T[size];
for (int i = 0, j = 0; i < m_length; i++, j++) {
if (i == index) {
new_arr[j] = obj;
j++;
}
new_arr[j] = m_arr[i];
}
delete[] m_arr;
m_arr = new_arr;
m_capacity = m_capacity * 2;
m_length++;
} else throw ("Index out of bounds!");
}
template<class T>
void DynamicArray<T>::remove(int index) {
if (index < m_length && index >= 0) {
T *new_arr = new T[m_capacity];
for (int i = 0, j = 0; i < m_length; i++, j++) {
if (i == index) i++;
if(i < m_length) new_arr[j] = m_arr[i];
}
delete[] m_arr;
m_arr = new_arr;
m_capacity = m_capacity * 2;
m_length--;
} else throw ("Index out of bounds!");
}
template<class T>
int DynamicArray<T>::size() {
return m_length;
}
template<class T>
void DynamicArray<T>::print() {
std::cout << m_arr[0];
for (int i = 1; i < m_length; i++) {
std::cout << ", " << m_arr[i];
}
}
std::vector
? Implementingvector
well, is a fairly non-trivial task even for people with a lot of experience. \$\endgroup\$