Take the 2-minute tour ×

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.

share|improve this question
You could use move semantics, if you have access to C++11. –  Xymostech Dec 5 '12 at 5:13
@Xymostech, I was just about to mention that :) –  chris Dec 5 '12 at 5:13
What you're looking for are expression templates. Boost.UBLAS uses them to great effect. Boost.Proto can help you make your own. –  GManNickG Dec 5 '12 at 5:15
Are you sure that it is being copied? The compiler may be allowed to eliminate that copy. Search for NVRO. –  Robᵩ Dec 5 '12 at 5:52
add comment

1 Answer

up vote 6 down vote accepted

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.

share|improve this answer
add comment

Your Answer


