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"
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....
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.operator-
, and in your second example you take by value. This is OK, except you have a second bug:Array
class has an internal buffer that it new
s on construction, and delete
s when it gets destroyed (~Array
).mx
is copied.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 delete
d; some time later, the other copy tries to do the same, and delete
ing the same buffer twice is an error.My suggestions:
operator=
into your class Array
. Very important.operator-
take a reference anyway. It makes mores sense.Hope that helps.