不是“const”当通过值时冗余? [英] Isn't "const" redundant when passing by value?

查看:179
本文介绍了不是“const”当通过值时冗余?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我遇到一个计算立方体体积的函数时,我正在阅读我的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.

这篇关于不是“const”当通过值时冗余?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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