Use of #39;const#39; for function parameters(对函数参数使用“const)
问题描述
const
你能走多远?你是只在必要时制作函数 const
还是全力以赴并在任何地方使用它?例如,想象一个简单的 mutator,它接受一个布尔参数:
How far do you go with const
? Do you just make functions const
when necessary or do you go the whole hog and use it everywhere? For example, imagine a simple mutator that takes a single boolean parameter:
void SetValue(const bool b) { my_val_ = b; }
那 const
真的有用吗?我个人选择广泛使用它,包括参数,但在这种情况下我想知道它是否值得?
Is that const
actually useful? Personally I opt to use it extensively, including parameters, but in this case I wonder if it's worthwhile?
我还惊讶地发现,您可以在函数声明的参数中省略 const
,但可以将其包含在函数定义中,例如:
I was also surprised to learn that you can omit const
from parameters in a function declaration but can include it in the function definition, e.g.:
.h 文件
void func(int n, long l);
.cpp 文件
void func(const int n, const long l)
这是有原因的吗?这对我来说似乎有点不寻常.
Is there a reason for this? It seems a little unusual to me.
推荐答案
原因是参数的 const
仅适用于函数内的本地,因为它正在处理数据的副本.这意味着函数签名无论如何都是一样的.不过,经常这样做可能是不好的风格.
The reason is that const
for the parameter only applies locally within the function, since it is working on a copy of the data. This means the function signature is really the same anyways. It's probably bad style to do this a lot though.
我个人倾向于不使用 const
除了引用和指针参数.对于复制的对象,这并不重要,尽管它可以更安全,因为它在函数内发出意图信号.这真的是一个判断电话.我确实倾向于使用 const_iterator
虽然在循环某些东西时我不打算修改它,所以我猜每个人自己的,只要 const
正确性以供参考types 得到严格维护.
I personally tend to not use const
except for reference and pointer parameters. For copied objects it doesn't really matter, although it can be safer as it signals intent within the function. It's really a judgement call. I do tend to use const_iterator
though when looping on something and I don't intend on modifying it, so I guess to each his own, as long as const
correctness for reference types is rigorously maintained.
这篇关于对函数参数使用“const"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:对函数参数使用“const"
基础教程推荐
- C++中的atoi 函数简介 2023-01-05
- C++详细实现完整图书管理功能 2023-04-04
- 一文带你了解C++中的字符替换方法 2023-07-20
- C/C++编程中const的使用详解 2023-03-26
- 如何C++使用模板特化功能 2023-03-05
- C语言基础全局变量与局部变量教程详解 2022-12-31
- 详解c# Emit技术 2023-03-25
- C语言 structural body结构体详解用法 2022-12-06
- C++使用easyX库实现三星环绕效果流程详解 2023-06-26
- C利用语言实现数据结构之队列 2022-11-22