I use the following code
Matrix operator * (const Matrix & obj)
{
Matrix m = Matrix();
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
{
m[i][j] = 0;
for (int k = 0; k < 4; k++)
m[i][j] += _data[i][k] * obj._data[k][j];
}
return m;
}
like this
v1 = m_proj * m_view * m_object * v1;
But I guess it is very unoptimized since I presume the new Matrix I create inside the operator is being copied around like crazy. If I do this though
Matrix & operator * (const Matrix & obj)
{
Matrix m = Matrix();
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
{
m[i][j] = 0;
for (int k = 0; k < 4; k++)
m[i][j] += _data[i][k] * obj._data[k][j];
}
return m;
}
Change the return type of the operator to a reference to Matrix the whole code stops working altogether (it compiles, just the matrices are not being multiplied as they should).
If I change it to
Matrix & operator * (const Matrix & obj)
{
Matrix & m = * new Matrix();
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
{
m[i][j] = 0;
for (int k = 0; k < 4; k++)
m[i][j] += _data[i][k] * obj._data[k][j];
}
return m;
}
Now it works but I have a bad memory leak.
So how do I solve this problem? Is there an elegant solution?
Thanks!
Your function is creating a new object, and it should return the object by value.
You cannot return references to a local variable, and returning references to dynamically allocated memory has multiple issues: it solves nothing (does not reduce the number of objects created by the expression, and makes each object more expensive to create due to the dynamic allocation) and adds memory leaks.
Without the definition of the class
Matrixit is not clear whether the memory is handled in an array or it is dynamically allocated. If it is dynamically allocated and you have a C++11 compiler, you can implement move construction and move assignment and the cost of all those copies will go away.In C++03 (and also in C++11) you can implement
operator*=and manually handle the objects that get created (assuming that you can do this in place efficiently):This will create a single temporary and apply all the multiplications in place, reducing the number of copies.
At any rate, I would not spend too much time with this, as a 4×4 matrix is not that expensive to copy.