Note: I'm using the visual studio community 2019 C++14 compiler.
It seems that the following program is trying to delete an empty location. I'm trying to delete a custom vector class after calling the + operator on it...
Here is the code:
class Vector
{
public:
Vector(const double* t, int dim) : m_dim(dim)
{
m_t = new double[dim];
for (int i = 0; i < dim; i++) {
m_t[i] = t[i];
}
}
~Vector() {
delete[] m_t;
}
Vector operator+(const Vector& v) {
Vector tmp{ v };
for (int i = 0; i < v.m_dim; i++) {
tmp.m_t[i] = tmp.m_t[i] + m_t[i];
}
return tmp;
}
private:
double* m_t;
int m_dim = 0;
};
int main() {
double t[] = { 1,2,3 };
Vector a{ t, 3 };
Vector b{ t, 3 };
Vector c{ t, 3 };
a = b + c;
// a answer is wrong,
// destructor, wntdll.pdb not loaded correctly
}
I think the error has to do something with the + operator deleting the "tmp" object before returning a value. I just can't figure out how to fix it. I tried replacing it with a pointer and a "new" operator, but it didn't work.
Thanks for @AlZ23z and @Ted Lyngmo for answers. The rule of three must be applied saying that there must be a =operator, copy constructor and destructor for the function.
Vector(const Vector&);
~Vector();
void operator=(const Vector&);
void Vector::operator=(const Vector& v)
{
for (int i = 0; i < m_dim; i++) {
m_t[i] = v.m_t[i];
}
}