If we have an object say a1 of type Array and if we have a line like a1 = a1 somewhere,
the program results in unpredictable behavior because there is no self
assignment check in the above code. To avoid the above issue, self
assignment check must be there while overloading assignment operator.
For example, following code does self assignment check.
// Overloaded assignment operator for class Array (with self // assignment check)Array& Array::operator = (const Array &rhs){ /* SELF ASSIGNMENT CHECK */ if(this != &rhs) { // Deallocate old memory delete [] ptr; // allocate new space ptr = new int [rhs.size]; // copy values size = rhs.size; for(int i = 0; i < size; i++) ptr[i] = rhs.ptr[i]; } return *this; }There is minor issue with above code. Even though we are doing self assignment check, there is a probability of corrupting the state of current/lefthad side object.We are doing delete[] ptr; //which is the member of Array class.And then we are re-allocating the memory, what if there is a exception thrownduring allocation of memory?? BAD_ALLOW,NO_MEM?To avoid such problems, first copy the ptr to local_ptr , allocate memory an then delete the old memory.Array& Array::operator = (const Array &rhs){ /* SELF ASSIGNMENT CHECK */ if(this != &rhs) { int *local_ptr = ptr; // allocate new space ptr = new int [rhs.size]; // Deallocate old memory delete [] local_ptr; // copy values size = rhs.size; for(int i = 0; i < size; i++) ptr[i] = rhs.ptr[i]; } return *this; }
No comments:
Post a Comment