I have a Class that is meant to represent a vector with an unspecified number of dimensions, VectorN:
int Size = 0;
VectorN::VectorN(int L)
{
Size = L;
Dimentions = new double[L];
}
VectorN::~VectorN()
{
delete[] Dimentions;
}
VectorN VectorN::operator+(const VectorN &rhs)
{
VectorN r = VectorN(this->Size);
for (int i = 0; i < Size; i++)
{
r[i] = Dimentions[i] + rhs.Dimentions[i];
}
return r;
}
double& VectorN::operator[](int arg)
{
return Dimentions[arg];
}
And this is used in my main function in the lines:
VectorN test = VectorN(1);
test[0] = 1;
VectorN test2 = VectorN(1);
test2[0] = 1;
VectorN test3 = VectorN(1);
test3 = test + test2;
However after the last line the program hits a "breakpoint" with the message "Invalid address specified to RtlValidateHeap"
What I think is happening is that the line
test3 = test + test2;
is causing the issue by creating a temporary instance of VectorN with
test + test2
which is then copied into test3 and the temporary version is then deleted because it's gone out of scope in the addition function, however since it's still being referenced in test3 the compiler has a problem because it's trying to delete a variable that's still being tracked. (please take this with a grain of salt, I'm not an expert on C++ so this might be entirely wrong.)
I suppose I could fix this by simply passing a pointer to the object created in the overloaded addition function, however I'd rather not risk memory leaks by having to manually delete a created instance every time I use addition with the class.