Consider the following implemntation of a Binary class representation of an integer:
class Binary {
private:
int *digits;
int first1;
public:
Binary() {
digits = new int[128];
digits[0]=0;
first1=0;
}
~Binary() {
cout<<"deleting"<<endl;
delete [] digits;
}
Binary(const Binary& b){
digits = new int[128];
memcpy(digits,b.digits,128*sizeof(int));
first1=b.first1;
}
explicit Binary(double x){
int n=(int)x,i;
digits = new int[128];
for (i=0; n ; i++,n>>=1) digits[i]=(n & 1)? 1:0;
first1=i-1;
}
Binary& operator =(const Binary& b){
if (this==&b) return *this;
memcpy(digits,b.digits,128*sizeof(int));
first1=b.first1;
return *this;
}
Binary(int n) {
int i;
digits = new int[128];
for (i=0; n ; i++,n>>=1) digits[i]=(n & 1)? 1:0;
first1=i-1;
}
void print() {
for (int i=first1; i>=0 ; i--) cout<<digits[i];
cout<<endl;
}
operator int() {
int x = 1,sum=0;
for (int i=0; i<=first1 ; i++,x<<=1) sum+=digits[i]*x;
return sum;
}
Binary& operator +(Binary& a) {
int overflow = 0;
Binary* b1=new Binary();
int max = a.first1>this->first1? a.first1 : this->first1,bit;
for (int i=0; i<=max ; i++) {
bit=a.digits[i]+this->digits[i]+overflow;
overflow=0;
if (bit>1) overflow=1;
b1->digits[i]=bit%2;
}
return *b1;
}
};
and the main using it:
int main() {
Binary b(91);
int x=9;
Binary *b2=new Binary();
*b2=b+x;
x=*b2;
b2->print();
cout<<" = "<<x;
cin>>x;
}
lets talk about the line:
*b2=b+x;
first the compiler implicitly allocates a new binary instance for int x, then using it as a paramater for the addition, then creates a new binary instance for the addition result and copies it bit by bit to *b2.
The problem is, that if you run this code, it only prints deleting ONCE, while there were 2 objects created for the execution of the command. apparently there's a leak comes from the addition code, in which i explicitly created a new object to return the result.
Q1: am i correct?
Q2: what can i do to overcome this?
EDIT: The answer and more about the topic of operator overloading can be found here