const通过引用使用const的点是什么? C ++ [英] What is the point of const being used with pass by reference? C++

查看:119
本文介绍了const通过引用使用const的点是什么? C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在读一本关于C ++的书,有一个例子,他们通过引用一个常量到一个函数。

I was reading a book on C++ and there was an example where they passed by reference a constant to a function.

int square(const int& n)
 ...

点这个?为什么不通过它的值正常传递它,如果你不会对变量进行任何更改。

I can't see the point of this? Why not just pass it normally by value if you are not going to be making any changes to the variable. Isn't the whole point of passing by reference so you can change the value of a variable.

推荐答案

对于复杂类型,传递by值比通过引用传递要贵得多,因为值的副本必须传递给函数。考虑向计算中值的函数传递一个大向量。你真的想分配一个新的向量,复制所有的值,在新的向量执行平均,然后释放你分配的内存?通过引用保存分配/复制/自由周期。

For complex types, passing by value is much more expensive than passing by reference because a copy of the value has to be made to pass to the function. Consider passing a large vector to a function that computes the median value. Do you really want to allocate a new vector, copy all the values in, perform the average over the new vector, and then free the memory you allocated? Passing by reference saves the allocate/copy/free cycle.

对于 int ,没关系。事实上,在大多数平台上通过价值会更便宜。

For int, it doesn't matter. In fact, on most platforms passing by value will be cheaper.

这篇关于const通过引用使用const的点是什么? C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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