c ++ - 为什么`const类型&变量作为函数输入? [英] c++ - why `const type& variable` as function input?

查看:172
本文介绍了c ++ - 为什么`const类型&变量作为函数输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将一些函数从Matlab转换为C ++,并且有一些与矩阵有关。我在Internet上的某个地方找到了这个简单的函数:

I'm converting some functions from Matlab to C++, and there are something to do with matrix. I found this simple function somewhere on the Internet:

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;
}



< a 作为输入,而不是 Matrix a ?他们使用它作为一种习惯,或使用它有任何好处,因为我没有看到两个版本的结果之间的任何差异( const Matrix& a Matrix a 作为输入)。

Can anyone explain me why they used const Matrix& a as the input, instead of Matrix a? Are they using it as a habit, or is there any benefit of using it since I did not see any difference between the results of 2 versions (const Matrix& a and Matrix a as input).

推荐答案


  • 是避免复制大型对象。然而,对于小对象,更优选具有非引用,因为引用创建将比它将保存更多的开销。例如,给定平台上的< = pointer-size 数据类型。

  • const 是确保给定的对象不会被函数改变,这是程序员写给定函数的安全检查,调用者的合同。

  • 有些人可能会认为 const 没有引用doesn' t有意义(因为原始对象不会被修改)。但是,作为一个安全网,建议函数实现者具有 const 参数,这样错误的函数不会改变其参数。这就是为什么,一些函数式语言默认情况下有 constness (除非你使它们可变)。

    • Reference is to avoid copying large size objects. However, for small objects, it is more preferable to have non-reference, since reference-creation will incur more overhead than it would save. For example <=pointer-size data type on a given platform.
    • const is to make sure that given object will not be changed by function, which is a safety-check for the programmer writing given function, a contract for the caller. It also makes the caller to pass a non-const as well as const object.
    • Some may argue that const without reference doesn't make sense (as original object will not be modified anyway). But, as a safety-net, it is advised for function implementer to have const parameters, so that by mistake function doesn't change its arguments. That's the reason, some functional languages have constness by default (unless you make them mutable).
    • 这篇关于c ++ - 为什么`const类型&amp;变量作为函数输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆