Isn#39;t quot;constquot; redundant when passing by value?(不是“常量吗?按值传递时多余?)
问题描述
我在阅读我的 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.
这篇关于不是“常量"吗?按值传递时多余?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:不是“常量"吗?按值传递时多余?


基础教程推荐
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- CString 到 char* 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01