我应该声明一个永远不会更改为const变量的参数? [英] Should I declare a parameter that will never be changed as a const variable?

查看:125
本文介绍了我应该声明一个永远不会更改为const变量的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

对函数参数使用'const'

例如,

void Func(int para);

如果我知道我不想更改Func我改为声明para作为const int来保证?即

If I know I don't want to change para's value in Func(...), should I instead declare para as "const int" to guarantee that? i.e.

void Func(const int para);

BTW,我认为

void Func(const int &para);

有时候因为const int&通常由底层指针实现,因此它基本上等效于

is not an appropriate alternative sometimes because const int& is usually implemented by underlying pointer, thus it is essentially equivalent to

void Func(const int *p_para);

本书C ++编码标准:101规则p31说void Func ;是坏的,因为它会头痛读者的头文件。我不知道是否...

The book "C++ Coding Standards: 101 Rules" p31 says that "void Func(const int para);" is bad as it will "confuse" the readers of the header files. I'm not sure though...

我想一个很好的解决方案是声明为void Func(int para);并在实现它时使用void Func(const int para){...}。我发现在void Func(const int para);将被编译器默认删除...

After thought it over, I think a good solution is to declare it as "void Func(int para);" and use "void Func(const int para) {...}" when implement it. I find that the word "const" in "void Func(const int para);" will be silently dropped by the compiler...

推荐答案

如果你这么做(有些人做)把const放在定义中(在这里它是有用的),而不是声明(它是噪声,它不会影响调用者)。

If you do this at all (and some people do) then you should put the const in the definition (where it is useful) but not the declaration (where it is noise, it doesn't affect the caller).

p>

So:

void F(int param);

...


void F(int const param) {
   ...
}

这篇关于我应该声明一个永远不会更改为const变量的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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