I am writing an array class template but have trouble with the destructor.
#ifndef ARRAY_CPP
#define ARRAY_CPP
using namespace std;
#include<iostream>
#include<sstream>
#include "Array.h"
//Define default constructor, initialize an array of size 10 with all elements being (0,0)
template<typename T> //Define type parameter
Array<T>::Array() {
size = 10;
m_data = new T[size];
}
template<typename T> //Define type parameter
Array<T>::Array(int si) {
size = si;
m_data = new T[size];
}
template<typename T> //Define type parameter
Array<T>::Array(const Array<T>& source) {
size = source.size; //Set the size equal to the size of the source
m_data = new T[size]; //Create a new source on the heap
//Loop through and copy each member of the source array to the new array
for (int i = 0; i < size; i++) {
m_data [i] = source.m_data [i];
}
}
//Define default destructor
template<typename T> //Define type parameter
Array<T>::~Array() {
delete[] m_data;
}
//Define operator =
template<typename T> //Define type parameter
Array<T>& Array<T>::operator = (const Array<T>& source) {
//Check self-assignment
if (this != &source) {
//Delete the old array
delete[] m_data;
size = source.size; //Set the size equal to the size of the source
m_data = source.m_data; //Set the dynamic C array equal to that of the source
//Loop through each element and copy each member of the source array to the current array
for (int i = 0; i < size; i++) {
m_data[i] = source.m_data [i];
}
}
//Return current array
return *this;
}
//Define operator[]
template<typename T> //Define type parameter
T& Array<T>::operator[](int index) {
if ((index < 0) || (index>= size))
throw -1;
return m_data[index];
}
//Define constant operator[]
template<typename T> //Define type parameter
const T& Array<T>::operator [] (int index) const {
if ((index < 0) || (index >= size))
throw -1;
return m_data[index];
}
using namespace std;
#include<iostream>
#include<sstream>
#include "Array.cpp"
void main() {
Array<double> test(10);
Array<double> test2(10);
test2 = test;
}
Whenever the destructor of array is called in main, it gives me error: Invalid address specified to RtlValidateHeap. I understand that this is because I am trying to delete memory on the stack. However, in my constructor, I initialize the array using new and this should create memory on the heap...The code worked well before I implemented template. Many thanks in advance !