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
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- C++,'if' 表达式中的变量声明 2021-01-01
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 设计字符串本地化的最佳方法 2022-01-01
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04