So, I have not written c++ in quite a while and am trying to dig back in to it. I am running in to a weird situation and I am hoping someone might be able to explain it.
I have a class representing a three dimensional matrix of integers in which I am trying to implement the operator+ for addition of an integer to all elements of the matrix. The class signature looks like this,

class Matrix

{

public:

Matrix();


Matrix(const Matrix& _object);

Matrix(const unsigned int _iMax, const unsigned int _jMax, const unsigned int _kMax);


~Matrix();


Matrix& operator=(const Matrix& rhs);


Matrix& operator=(const int& rhs);


Matrix operator+(const int& rhs) const;

};

When I first implemented this class I did not include the copy constructor. Without the copy constructor, if I ran the simple test code below I consistently saw an error indicating a memory violation. What was happening is when the object mat3 was destroyed the memory used internally to store the integer matrix had already been cleaned up.

int main(int argc, char* argv[])

{

Matrix mat(5, 5, 5);

mat = 0;


Matrix mat3;

mat3 = mat + 1;


return 0;

}

I managed to track this down in the debugger to determine that the temporary object returned by operator+(int) actually used the same address for storage of the internal array of data that the object mat3 did. So, when the temporary object was cleaned up it deallocated the memory.
On a whim, I added the copy constructor to see if the behavior was different. Sure enough, when I define the copy constructor the compiler is converting the line,
to

mat3.operator=(new Matrix(mat.operator+(1)))

thus inserting the call to the constructor. In this case everything works with no problems at all.
What I am wondering is if this should be required, or if I have a problem in the implementation of my + and = operators. I really dislike having yet another class instantiation and copy here since the internal matrix could be big. Hate to use the memory as well as have to copy the data.
My operators + and = are implemented as shown below,

Matrix& Matrix::operator=(const Matrix& rhs)

{

iMax = rhs.iMax;

jMax = rhs.jMax;

kMax = rhs.kMax;


if (data!= 0)

{

delete [] data;

}


data = new int[iMax * jMax * kMax];

for (unsigned int ijk = 0; ijk < iMax * jMax * kMax; ijk++)

{

data[ijk] = rhs.data[ijk];

}


return *this;

}



Matrix Matrix::operator+(const int& rhs) const

{

Matrix newMat(iMax, jMax, kMax);


for (unsigned int ijk = 0; ijk < iMax * jMax * kMax; ijk++)

{

newMat.data[ijk] = data[ijk] + rhs;

}


return newMat;

}

I appreciate any help on this.