不是“常量"吗?按值传递时多余?
我在阅读我的 C++ 书籍 (Deitel) 时遇到了一个计算立方体体积的函数.代码如下:
I was reading my C++ book (Deitel) when I came across a function to calculate the volume of a cube. The code is the following:
double cube (const double side){
return side * side * side;
}
使用const"限定符的解释是这样的:const 限定符应该用于强制执行最小权限原则,告诉编译器函数不修改变量端".
The explanation for using the "const" qualifier was this one: "The const qualified should be used to enforce the principle of least privilege, telling the compiler that the function does not modify variable side".
我的问题:这里使用const"不是多余/不必要的,因为变量是按值传递的,所以函数无论如何都不能修改它?
My question: isn't the use of "const" redundant/unnecessary here since the variable is being passed by value, so the function can't modify it anyway?
推荐答案
const
限定符防止函数内部的代码修改参数本身.当函数大于普通大小时,这种保证可以帮助您快速阅读和理解函数.如果您知道 side
的值不会改变,那么您不必担心在阅读时跟踪它的值.在某些情况下,这甚至可以帮助编译器生成更好的代码.
The const
qualifier prevents code inside the function from modifying the parameter itself. When a function is larger than trivial size, such an assurance helps you to quickly read and understand a function. If you know that the value of side
won't change, then you don't have to worry about keeping track of its value over time as you read. Under some circumstances, this might even help the compiler generate better code.
考虑到这通常是一种很好的风格,有不少人这样做是理所当然的.
A non-trivial number of people do this as a matter of course, considering it generally good style.
相关文章