0

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.

Lorand
  • 193
  • 3
  • 18
  • 1
    https://en.cppreference.com/w/cpp/language/rule_of_three – ALX23z Jun 14 '21 at 10:22
  • ... and [Rule-of-Three becomes Rule-of-Five with C++11?](https://stackoverflow.com/questions/4782757/rule-of-three-becomes-rule-of-five-with-c11) – Ted Lyngmo Jun 14 '21 at 10:43

1 Answers1

1

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];
       }
}

https://en.cppreference.com/w/cpp/language/rule_of_three

Lorand
  • 193
  • 3
  • 18
  • Note that the expected signature for the copy assignment operator is `Vector& Vector::operator=(const Vector&)` - so you should change that and then `return *this;`. Also check and prevent self-assignment. – Ted Lyngmo Jun 14 '21 at 12:20