Say we make a Matrix<n, m>
class, that stores nxm integers in a member variable std::array<std::array<int, m>, n> inner;
. Now there are two ways of making add:
Method 1) Returning by value (constexpr
is possible)
template<int n, int m> class Matrix {
...
constexpr Matrix add(const Matrix& that) const {
matrix ret;
for (int y = 0; y < n; y++)
for (int x = 0; x < m; x++)
ret.inner[y][x] = this->inner[y][x] + that.inner[y][x];
return ret;
}
...
}
Method 2) Returning a pointer (constexpr
is not possible)
template<int n, int m> class Matrix {
...
Matrix *add(const Matrix& that) const {
Matrix *ret = new Matrix();
for (int y = 0; y < n; y++)
for (int x = 0; x < m; x++)
ret->inner[y][x] = this->inner[y][x] + that.inner[y][x];
return ret;
}
...
}
My program need to do arithmetic with 1000x1000
matrices (images), so using Method 1 I get a stackoverflow immediately. My program also works with small 4x4
matrices (density matrices in quantum computations) that need to be computed at compile time, so using Method 2 is impossible in these constexpr
initializations.
Question: do I need to make two versions of every method returning Matrix
? (one returning a Matrix
and the other returning a Matrix*
) This will be a lot of duplicate code. How common is this problem? Is there an alternative way of using the heap so that Method 2 is also possible from constexpr
?
This answer mentions that move-semantics have shifted the preference a little bit to Method 1. But how about the resulting stack-overflows?