I'm trying to write a C++ Class for managing data in a specific way. More Specific: to mimic mathmatical Matrix behavior like matrix-multiplication and stuff like that with as little overhead as possible. Intuitively i would like to use overloaded operators for better readability, but i always wonder about the additional allocation for returning the result-Matrix. Especially regarding performance if you think about a really large Matrix.
So far, i got everything set up to allocate and correctly access the stored Data by providing dimension coordinates. The objects are Heap allocated as Pointers to do some fancy stuff with transforming the Matrix. Adding looks like this so far:
Matrix* Add(Matrix* A, Matrix* B, Matrix* result)
{
[...] //Math here
return result;
}
So when calculating, the result is directly written into the result object since its acessed via Pointer.
But when using operator overloading, my confusion starts to grow. I would implement something like this (simplified, minimal problem):
Matrix* operator+(Matrix& other)
{
Matrix* result = new Matrix;
[...] //Math here
return result;
}
Imagine we live in a perfect world and leackage is magically solved, there is still the problem, that i dont see a way around allocating memory for the result internally. If i already have the object preallocated or i recycle one from previous calculations, isn't allocating the result memory waste of computational power? Is there a more efficient way around this or is maybe somehow internally optimized in a way i dont know of?