Assignment Operator Copies negative values instead of actual values

I'm writing the overload for the assignment operator for an object that has a pointer to an int array inside of it. The assignment operator does not work 100% of the time. If I do something simple, such as A = B, where A and B are both the objects I am working with, then it works fine, and the values are copied from B to A. However, if I write code such as A = B = C = D, the assignment operator does not work.

I debugged my code and ran a couple of tests. First, I just printed out the array's values before the line of code A = B = C = D. The values from the array printed out just fine. I also did A = B, before A = B = C = D, and B's array values were assigned to A. Upon reaching A = B = C = D, the program could no longer read the array and instead read the value of each index of all the arrays as some random long negative number. Here is my code for the assignment operator.

1
2
3
4
5
6
7
8
9
10
11
12
Score& Score::operator=(const Score &other)
{
	int* temp = scoreArray;
	arraySize = other.arraySize;
	scoreArray = new int[arraySize];
	for(int i = 0; i < arraySize; i++)
	{
		scoreArray[i] = other.scoreArray[i];
	}
	delete [] temp;
	return *this;
}
I don't see anything wrong with that code.
Does it work if you replace that multiple assignment with
1
2
3
C = D;
B = C;
A = B;
?
If this == &other, then loop breaks : other.scoreArray is lost on line 5.
Canonical approach is to fill temporary array and swap it at the end:
1
2
3
4
5
6
7
8
9
10
11
Score& Score::operator=(const Score &other)
{
    using std::swap;
    arraySize = other.arraySize;
    int* temp = new int[arraySize];;
    for(int i = 0; i < arraySize; ++i)
        temp[i] = other.scoreArray[i];
    swap(temp, scoreArray);    
    delete [] temp;
    return *this;
}
Topic archived. No new replies allowed.