0

To illustrate my problem I minimalize my source:

#include <iostream>
class vec{
    public:
    float* X;
    int DIM;
    vec(int dimension)
    {
        DIM = dimension;
        X = new float[dimension];
        for (int i=0;i<DIM;i++)
            X[i] = (float) rand()/RAND_MAX;
    }
    ~vec(void){
        delete [] X;
    }

    vec operator-( vec const& rhs )
    {
        vec ans(DIM);
        for (int i=0;i<DIM;i++)
            ans.X[i] = X[i] - rhs.X[i];
        return ans;
    }
};

int main(){
    vec A(5),B(5),C(5);
    C= A-B;
    return 0;
}

When I execute this program I get an error that a heap was destroyed. I am pretty sure that the destructor is my problem. In the line with C= A-B; the variable ans will be destroyed by the constructor and cannot be returned. Is that right? If I delete the line delete [] X; everything is ok. But it won't free up the memory.

I did my homework and consult one of the most famous search engine for this problem but didn't find any answer. How can I fix it?

Suvarna Pattayil
  • 5,136
  • 5
  • 32
  • 59
  • `ans` getting destructed is not a problem. A temporary copy of `ans` is made and that is what is returned (in principle.) – Jacob Parker Mar 29 '13 at 11:04

1 Answers1

4

C = A-B calls the default copy-assignment operator (as you haven't defined one). Therefore two different objects will point to the same dynamically-allocated array.

You need to read up on the Rule of Three (in a nutshell: if you define any of the destructor, the copy constructor or the copy-assignment operator, you probably need to define them all).

But preferably, you should avoid using raw arrays entirely; use a container type that manages its own memory.

Community
  • 1
  • 1
Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680