# Is what I think is gonna happen gonna happen

• 02-04-2009
cunnus88
Is what I think is gonna happen gonna happen
I'm trying to get rid of some inefficiencies in my code. The current (simplified) version is this:

Code:

```class matrix { double data*; matrix& operator=(const matrix& m) { (for each element of m.data) { data[i] = m.data[i];}} matrix getminor(range_of_minor) { matrix m; copy_all_elements_of_this_in_range_to_m; return m;}}```
Then I would do this:
Code:

```matrix big_matrix, smaller_matrix; smaller_matrix = big_matrix.getminor(range_of_minor);```
Am I copying matrices twice in the above code? Once when matrix::getminor creates a minor matrix and once when it assigns it to another one? Would it be better if I rewrote the function so that smaller_matrix is passed by reference to matrix::getminor and the values of data are copied directly?
• 02-04-2009
Thantos
Maybe. However, I would imagine that any smart compiler would optimize out the second construction.
• 02-04-2009
phantomotap
Instead of relying on the compiler to do something clever in that context, overload a constructor to create the submatrix, the "minor" of ''matrix matrix::getminor(p1, ..., pn)', directly as the elements of a new matrix.

If you now have this:

Code:

```matrix a; matrix b; // ... b = a.getminor(x, y, cx, cy);```
You'll get thins:

Code:

```matrix a; // ... matrix b(a, x, y, cx, cy);```
(If there are any, you may want to lift the duplicate parts of 'matrix::matrix(const matrix &)', 'matrix & matrix::operator = (const matrix &)', 'matrix matrix::getminor(p1, ..., pn)', and 'void matrix::getminor(matrix &, p1, ..., pn)' out and put them in a shared function.)

Soma