Search code examples
c++memorydynamicparameterstransfer

c++ mystic transfer of class array


class Array
{
    double *mx; int mn;
public:

 Array();
~Array(){delete []mx};
 Array& operator-(Array& b);  //first right way
 Array operator -(Array b);  //wrong way, but I don't understand why
};

Array::Array ()
{ 
  mn=10;
  mx=new double[mn];
}

//first, works perfectly
Array& Array::operator -(Array& b)
{
    int i=0;

    for(i=0;i<mn ;i++)
       this->mx[i]-=b.mx[i];

  return *this;
 }


// here is Error

Array Array::operator -(Array b)
{ 
    int i=0;

    for(i=0;i<mn ;i++)
       this->mx[i]-=b.mx[i];

  }


int main() {
   Array x,b;
   x=x-b;
}

If I use the first overload , all works right.

But if I use the second, all is compiled well, but when program is executed, i receive many errors like this:

"c++ ** glibc detected *** double free or corruption" 

http://s41.radikal.ru/i091/1105/e1/2349397c04a2.png

I can't figure out why this occurs.

As I understand, when I call Array Array::operator-(Array b), the object must be copied and all must be well, but there is error.

well i've read that i've to object that are allocated at the same place in the memory. but i've tried to do this:

        Array Array::operator +(Array b)
 { Array c;
 int i=0;
 for(i=0;i<mn;i++) 
this->mx[i]+=b.mx[i];
 cout<<&this->mx<<" "<<&b.mx<<endl; 
exit(0);
 return c; }

i 've expected to receive same addresses in memory....

answer is 0xbfb45188 0xbfb45178 why are they equal?

furhermore, when i declare here name of class(A object)
compiler must give a new memory in stack for object where am i wrong? i dont understand....


Solution

    • operator- should take a reference, otherwise you're performing needless copies. However, it doesn't need to. It certainly should return a value, because a - semantically gives you a new object. When you write c = a-b, you don't expect a or b to change.
    • As noted above, you don't need to take a reference into operator-, and in your second example you take by value. This is OK, except you have a second bug:
      • Your Array class has an internal buffer that it news on construction, and deletes when it gets destroyed (~Array).
      • However, it does not have a user-defined copy constructor, and the buffer is not automatically copied for you; only the pointer mx is copied.
      • So, when you copy the Array, you now have two objects with a pointer mx pointing to the same buffer. When one copy goes out of scope, that buffer is deleted; some time later, the other copy tries to do the same, and deleteing the same buffer twice is an error.

    My suggestions:

    • Write a copy constructor and operator= into your class Array. Very important.
    • Have operator- take a reference anyway. It makes mores sense.

    Hope that helps.