删除“const”是否更好?在“原始”之前,在头中用作函数参数的类型? [英] Is it better to remove "const" in front of "primitive" types used as function parameters in the header?

查看:139
本文介绍了删除“const”是否更好?在“原始”之前,在头中用作函数参数的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在代码审查过程中,我的一位同事向我提到,在头中用作函数参数的基本类型之前的const是毫无意义的,他建议删除这些const。在这种情况下,他建议只在源文件中使用const。原始类型意味着像int,char,float等类型。

以下是示例。



example.h

  int ProcessScore(const int score); 

example.cc

  int ProcessScore(const int分数){
//使用分数
进行一些计算return some_value;
}

他的建议是这样做的:

example.h

  int ProcessScore(int score); / / const在这里被删除。 

example.cc

  int ProcessScore(const int分数){
//使用分数
进行一些计算return some_value;
}

但我有些困惑。通常,用户只会看标题,所以如果标题和源文件不一致,可能会引起混淆。

任何人都可以提供一些建议对于所有类型(不仅仅是基元),顶级类型 / strong>函数声明中的const限定符将被忽略。因此,下面的四个声明了相同的函数:

$ $ $ $ $ $ $ $ $> $ f $(int const i,int const j);
void foo(int i,int const j);
void foo(int const i,int j);
void foo(int i,int j);

然而,在函数 body 内不会忽略const限定符。它可以影响常量的正确性。但是这是该函数的实现细节。所以一般的共识是这样的:


  1. 把const放在声明之外。它只是混乱,并不影响客户端如何调用该函数。

  2. 如果你愿意,可以在定义中保留const 以便编译器捕捉参数的任何意外修改。


In the code review process, one of my coworkers mentioned to me that "const"s in front of "primitive types" used as a function parameter in a header is meaningless, and he recommended to remove these "const"s. He suggested using "const" only in the source file in such cases. Primitive types mean types such as "int", "char", "float", etc.

The following is example.

example.h

int ProcessScore(const int score);

example.cc

int ProcessScore(const int score) {
  // Do some calculation using score
  return some_value;
}

His suggestion is doing as follows:

example.h

int ProcessScore(int score);  // const is removed here.

example.cc

int ProcessScore(const int score) {
  // Do some calculation using score
  return some_value;
}

But I'm somewhat confused. Usually, the user will look at only the header, so if there is inconsistency between the header and the source file, it might cause confusion.

Could anyone give some advice on this?

解决方案

For all types (not just primitives), the top level const qualifiers in the function declaration are ignored. So the following four all declare the same function:

void foo(int const i, int const j);
void foo(int i, int const j);
void foo(int const i, int j);
void foo(int i, int j);

The const qualifier isn't ignored inside the function body, however. There it can have impact on const correctness. But that is an implementation detail of the function. So the general consensus is this:

  1. Leave the const out of the declaration. It's just clutter, and doesn't affect how clients will call the function.

  2. Leave the const in the definition if you wish for the compiler to catch any accidental modification of the parameter.

这篇关于删除“const”是否更好?在“原始”之前,在头中用作函数参数的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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