Reputation: 999
My class Matrix has two constructors including the copying one, which performs a deep copying. Such a solution works great for an obvious case of copying another object. Though in the following case:
Matrix m = m1 * m2; // for earlier constructed m1 & m2
It seems to me the to be inefficient, since I've created an object in multiplication operation only to get it copied instead of being directly assigned to m. And matrix can occupy a really huge piece of memory. How to handle it better, what is the common practice by the professionals?
Matrix is implemented dynamically as a two dimensional list, as in case of sparse matrices.
P.S. I understand that the result of multiplication is local. Still, however, I fell that it could be somehow handled better without the above-mentioned excessive computing.
Upvotes: 3
Views: 102
Reputation: 53047
In C++11 you could create a move constructor which should be faster in your case. I'm not going to explain how to do so as there's many tutorials already out there such as this: http://thbecker.net/articles/rvalue_references/section_01.html
You could also try expression templates which can be good at optimizing code like this, although the syntax will look different. See http://en.wikipedia.org/wiki/Expression_templates for getting started.
Upvotes: 6