C ++ - why `const type & variable` as function input?

I am converting some functions from Matlab to C ++, and something is related to the matrix. I found this simple function somewhere on the web:

typedef std::vector<std::vector<double> > Matrix;

Matrix sum(const Matrix& a, const Matrix& b) {
  size_t nrows = a.size();
  size_t ncols = a[0].size();
  Matrix c(nrows, std::vector<double>(ncols));
  for (int i = 0; i < nrows; ++i) {
    for (int j = 0; j < ncols; ++j) {
      c[i][j] = a[i][j] + b[i][j];
    }
  }
  return c;
}

Can someone explain to me why they used const Matrix& aas input and not Matrix a? Do they use it as a habit or is there any benefit from using it, since I did not see any difference between the results of the two versions ( const Matrix& aand Matrix aas input).

+4
source share
2 answers
  • . , , . , <=pointer-size .
  • const , , , , . const, const.
  • , const ( ). , - const, . constness ( ).
+6

, , - , .

A Matrix a . Matrix Matrix a, . 3x3 , ... 3x3 300x300, . , . , const Matrix& a, Matrix, - Matrix.

, Matrix & a, Matrix a, , . const Matrix & a promises , a , , , . . , .

+3

All Articles